validate a cell based on another cell value in datagrid in silverlight - xaml

PFB the code for datagrid in our silverlight app,i need to validate the column AttributeValue in each row based on other column value DatatypeName, for example the DatatypeNamecolumn value for a particular row is int the AttributeValue column in the same row should allow user only int ,if user enters other than int the cell should throw validation exception.Please help
<sdk:DataGrid Margin="0,0,0,50" Grid.Row="1" Grid.Column="0" RowStyle="{StaticResource DataGridRowStyle1}" Style="{StaticResource DataGridStyle1}" IsReadOnly="True" Foreground="{StaticResource GrayBrush}" HorizontalScrollBarVisibility="Hidden" Name="dgKpiAttributes" MinHeight="5" VerticalAlignment="Stretch" FontSize="13.333" FontFamily="Segoe UI" AutoGenerateColumns="False" GridLinesVisibility="None" >
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header=" " >
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="chkSelect"
VerticalAlignment="Center" IsChecked="False" HorizontalAlignment="Center" HorizontalContentAlignment="Center"/>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn Header="AttributeName" SortMemberPath="AttributeName" Width="50*" >
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center">
<TextBlock x:Name="txtAttributeName" TextWrapping="Wrap" Padding="4" Text="{Binding AttributeName}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn Header="AttributeValue" SortMemberPath="AttributeValue" Width="80*" >
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center">
<TextBox x:Name="AttributeValue" Margin="0,0,10,0" HorizontalAlignment="Stretch" Text="{Binding AttributeValue}" TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn Header="DataType" SortMemberPath="DataTypeName" Width="50*">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center">
<TextBox x:Name="DatatypeName" HorizontalAlignment="Stretch" TextWrapping="Wrap" IsEnabled="False" Text="{Binding DataTypeName}" />
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>

Well, from your code I can see your class is like this (correct me if I'm mistaken):
class MyClass
{
public string AttributeName {get;set;}
public string AttributeValue {get;set;}
public string DatatypeName {get;set;}
}
In silverligth, I suppose there is a way to check another cells in the same row in a datagrid, but since you are working with bindings, you do not need that, you can work directly in your data object:
class MyClass
{
public string AttributeName {get;set;}
public string DatatypeName {get;set;}
private string _AttributeValue;
public string AttributeValue {
get{
return _AttributeValue;
}
set{
if (validate(DatatypeName,value)){
//Do something if validation is a success
_AttributeValue = value;
}
else{
//Do something if validation fails
}
}
}
bool validate(string typename,string value){
//do your validation, return true or false
return true
}
}
This way you do not need to concern yourself with traversing the UI, only with the data.

Related

Binding IsSelected on ListViewItem not working for me in UWP application

I'm working with a list of objects that have a Selected property and I'm trying to bind it to the IsSelected property on ListViewItem within a multi-select ListView control in UWP.
I just can't seem to get the binding to work. The checkboxes in the ListView do not render checked if Selected = True and the Set on Selected never gets triggered when checking an item.
SettingsPage.xaml
<Page.Resources>
<DataTemplate x:Key="PreviewColumnTemplate" x:DataType="models:Column">
<TextBlock>
<Run Text="{x:Bind name}"/>
<Run Text=" ("/>
<Run Text="{x:Bind ColumnValidation.column_label}"/>
<Run Text=") "/>
</TextBlock>
</DataTemplate>
<Style x:Key="previewColumnListViewItem" TargetType="ListViewItem">
</Style>
</Page.Resources>
<ListView
x:Name="previewColumnListView"
ItemsSource="{x:Bind ViewModel.CurrentDrillHole.Collar.Columns, Mode=TwoWay}"
ItemTemplate="{StaticResource PreviewColumnTemplate}"
Height="400"
SelectionMode="Multiple"
SelectionChanged="previewColumnListView_SelectionChanged">
<ListView.Resources>
<Style TargetType="ListViewItem" BasedOn="{StaticResource previewColumnListViewItem}">
<Setter Property="IsSelected" Value="{Binding Selected, Mode=TwoWay}"/>
</Style>
</ListView.Resources>
</ListView>
The ViewModel.CurrentDrillHole.Collar object is of type Table and looks like so:
public class Table : BindableBase
{
public string Name { get; set; }
public TableValidation TableValidation { get; set; }
public List<Column> Columns { get; set; }
public List<Row> Rows { get; set; } = new List<Row>();
}
And the Column object looks like so. It is here I want to bind to the Selected property.
public class Column : BindableBase, INotifyPropertyChanged
{
public string name { get; set; }
public ColumnValidation ColumnValidation { get; set; }
public List<RefEntryValue> LookupValues { get; set; } = null;
private bool _selected = false;
public bool Selected {
get => _selected;
set
{
_selected = value;
OnPropertyChanged();
}
}
}
Any ideas of things I can try would be greatly appreciated. Thanks for the help!
When you set SelectionMode="Multiple", ListViewItem uses the default ListViewItemTemplate whose key is "ListViewItemExpanded".
Its style is as follows:
<Style TargetType="ListViewItem" x:Key="ListViewItemExpanded">
......
<ControlTemplate TargetType="ListViewItem">
<Grid x:Name="ContentBorder"
Control.IsTemplateFocusTarget="True"
FocusVisualMargin="{TemplateBinding FocusVisualMargin}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
RenderTransformOrigin="0.5,0.5">
……
<Border x:Name="MultiSelectSquare"
BorderBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
BorderThickness="2"
Width="20"
Height="20"
Margin="12,0,0,0"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Visibility="Collapsed">
<Border.Clip>
<RectangleGeometry Rect="0,0,20,20">
<RectangleGeometry.Transform>
<TranslateTransform x:Name="MultiSelectClipTransform" />
</RectangleGeometry.Transform>
</RectangleGeometry>
</Border.Clip>
<Border.RenderTransform>
<TranslateTransform x:Name="MultiSelectCheckBoxTransform" />
</Border.RenderTransform>
<FontIcon x:Name="MultiSelectCheck"
FontFamily="{ThemeResource SymbolThemeFontFamily}"
Glyph=""
FontSize="16"
Foreground="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
Visibility="Collapsed"
Opacity="0" />
</Border>
<Border x:Name="MultiArrangeOverlayTextBorder"
Opacity="0"
IsHitTestVisible="False"
Margin="12,0,0,0"
MinWidth="20"
Height="20"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Background="{ThemeResource SystemControlBackgroundAccentBrush}"
BorderThickness="2"
BorderBrush="{ThemeResource SystemControlBackgroundChromeWhiteBrush}">
<TextBlock x:Name="MultiArrangeOverlayText"
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplateSettings.DragItemsCount}"
Style="{ThemeResource CaptionTextBlockStyle}"
IsHitTestVisible="False"
Opacity="0"
VerticalAlignment="Center"
HorizontalAlignment="Center"
AutomationProperties.AccessibilityView="Raw" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Style>
As you can see, there is no CheckBox in its style, it is composed by Border and FontIcon.
If you want to solve this problem, I suggest that you could add CheckBox to DataTemplate. By doing this, we can bind “Selected’ to the “IsChecked” property of the CheckBox.
Please refer to the following code.
<ListView
x:Name="previewColumnListView"
ItemsSource="{x:Bind ViewModel.CurrentDrillHole.Collar.Columns, Mode=TwoWay}"
Height="400"
SelectionChanged="previewColumnListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate x:Key="PreviewColumnTemplate" x:DataType="models:Column">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Selected, Mode=TwoWay}"/>
<TextBlock>
<Run Text="{x:Bind name}"/>
<Run Text=" ("/>
<Run Text="{x:Bind ColumnValidation.column_label}"/>
<Run Text=") "/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This is how it ended up looking in the end. Does this seem clunky to anyone else? It would be nice if the ListView control made it easier to deal with collections and SelectionMode="Multiple".
SettingsPage.xaml
<ListView
x:Name="previewColumnListView"
ItemsSource="{x:Bind ViewModel.CurrentDrillHole.Collar.Columns, Mode=TwoWay}"
Height="400"
SelectionChanged="previewColumnListView_SelectionChanged"
IsItemClickEnabled="True"
ItemClick="previewColumnListView_ItemClick">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Column">
<StackPanel Orientation="Horizontal">
<CheckBox Click="previewColumnListView_CheckBox_Click" IsChecked="{Binding Selected, Mode=TwoWay}"/>
<TextBlock>
<Run Text="{x:Bind name}"/>
<Run Text=" ("/>
<Run Text="{x:Bind ColumnValidation.column_label}"/>
<Run Text=") "/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
SettingsPage.xaml.cs
private async void previewColumnListView_CheckBox_Click(object sender, RoutedEventArgs e)
{
// update the list of selected columns
Settings.CollarPreviewFields = ViewModel.CurrentDrillHole.Collar.Columns.Where(x => x.Selected).Select(x => x.name).ToList();
await App.SaveSettings();
}
private void previewColumnListView_ItemClick(object sender, ItemClickEventArgs e)
{
Column selectedColumn = (Column)e.ClickedItem;
selectedColumn.Selected = !selectedColumn.Selected;
// trigger checkbox click event. will update the list and save.
previewColumnListView_CheckBox_Click(null, null);
}

UWP Changing gridview element size programmatically

I'm trying to use XAML binding to affect the gridview datatemplate element size from a slider on my screen.
I have a gridview made of thumbnails images where the elements are defined as following:
<GridView.ItemTemplate >
<DataTemplate >
<StackPanel Orientation="Vertical"
HorizontalAlignment="Center"
VerticalAlignment="Center"
KeyDown="IsitenterThumb"
BorderBrush="LightSeaGreen"
BorderThickness="1"
PointerWheelChanged="ctlThumbnails_PointerWheelChanged">
<Image Source="{Binding thumb}"
x:Name="thumbimg"
Visibility="Visible"
Height="{Binding ItemSize}" Width="{Binding ItemSize, ElementName=page}" Stretch="Uniform"
Tapped="ThumbnailSelected"
DoubleTapped="CloseThumbnails"
/>
<TextBlock Text="{Binding name}" Margin="5,5"
Foreground="White"
Width="{Binding ItemSize}"
/>
</StackPanel>
</DataTemplate>
And I have the following variable defined as follow:
public double ItemSize
{
get => _itemSize;
set
{
if (_itemSize != value)
{
_itemSize = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ItemSize)));
}
}
}
private double _itemSize;
public event PropertyChangedEventHandler PropertyChanged;
I would have thought that changing the value of ItemSize would have affected the gridview datatemplate. This is taken litterally from the PhotoLab sample.
Instead I get a single huge "thumbimg" per page... Any help would be greatly appreciated!
Ok... I got it finally. I'm not quite sure what I was doing wrong above, but the code below works.
I have put the DataTemplate as part of a Page.Resource, I'm not sure if this is what was causing the binding issue. However the Xaml code looks like this:
<Page.Resources>
<DataTemplate x:Key="ThumbnailsTemplate">
<StackPanel Orientation="Vertical"
HorizontalAlignment="Center"
VerticalAlignment="Center"
KeyDown="IsitenterThumb"
BorderBrush="LightSeaGreen"
BorderThickness="1"
<Image Source="{Binding thumb}"
x:Name="thumbimg"
Visibility="Visible"
Height="{Binding ItemSize, ElementName=page}" Width="{Binding ItemSize, ElementName=page}"
Stretch="Uniform"
Tapped="ThumbnailSelected"
DoubleTapped="CloseThumbnails"
/>
<TextBlock Text="{Binding name}" Margin="5,5"
Foreground="White" Width="{Binding ItemSize}"
/>
</StackPanel>
</DataTemplate>
</Page.Resources>
<GridView x:Name = "ctlThumbnails" Grid.Column="0"
BorderBrush="White" BorderThickness="2"
Grid.RowSpan="4" Grid.Row="0" Grid.ColumnSpan="3" Height ="auto" Width="auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Margin="30,30,30,30" KeyDown="IsitenterThumb"
DoubleTapped="CloseThumbnails"
ItemTemplate="{StaticResource ThumbnailsTemplate}">
</GridView>
And here is the C# code to affect the bound variable ItemSize
public event PropertyChangedEventHandler PropertyChanged;
public double ItemSize
{
get => _itemSize;
set
{
if (_itemSize != value)
{
_itemSize = value;
topcmdbarcontent.Text = "Thumb Size:" + _itemSize.ToString();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ItemSize)));
}
}
}
private double _itemSize;
From this, when you change the value of ItemSize, through a ValueChanged event, for example, it does change the grid element size dynamically.

UWP Exception when binding to ComboBox

I am getting this exception:
An unhandled win32 exception occurred in AppName.exe
This occurs only when I Bind to a ComboBox
Here's my XAML:
<ContentDialog x:Name="BrowseBySourceDialog"
Grid.Column="1"
PrimaryButtonText="Accept" IsPrimaryButtonEnabled="False"
Opened="BrowseBySourceDialog_Opened">
<StackPanel Background="White">
<Border Background="DarkGreen" MinHeight="40"
MinWidth="300">
<TextBlock Text="Browse: By Source"
VerticalAlignment="Center"
Foreground="White"
TextAlignment="Center"
HorizontalAlignment="Center" />
</Border>
<StackPanel>
<ComboBox x:Name="BrowseBySourceComboBox"
PlaceholderText="Select Source"
Height="40"
Width="300"
ItemsSource="{x:Bind BrowseBySourceList, Mode=OneWay}"
DisplayMemberPath="Source">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="local:FeaturedResponseItem">
<TextBlock Text="{x:Bind key}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</StackPanel>
</ContentDialog>
This exception only occurs when the following lines are present:
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="local:FeaturedResponseItem">
<TextBlock Text="{x:Bind key}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
If the remove the above lines, the combobox surely remains empty but the exception doesn't occur. Is the binding wrong?
Source:
ObservableCollection<FeaturedResponseItem> BrowseBySourceList { get; set; } = new ObservableCollection<FeaturedResponseItem>();
Model:
public class FeaturedResponseItem
{
public string key { get; set; }
public string icon { get; set; }
public bool accessible { get; set; }
}
You can delete DisplayMemberPath="Source" or simply just remove the ItemTemplate all together and change DisplayMemberPath="Source" to DisplayMemberPath="Key".

XAML Gridview to add an item directly

I successfully coded an XAML Gridview to show list of items.
However, I want to add an [+(ADD ITEM)] button at the end of the Gridview.
The ADD button has should have a custom template (at least a default button) which is different from the content item.
My XAML source is below:
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemsGridView"
AutomationProperties.Name="Items"
TabIndex="1"
Grid.RowSpan="2"
Padding="116,136,116,46"
ItemsSource="{Binding Source={StaticResource DataSource}}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Width="250" Height="250">
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding Subject}" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" Height="60" Margin="15,0,15,0" FontWeight="SemiBold"/>
<TextBlock Text="{Binding TargetDate}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,15,10" FontSize="12"/>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<!--
Something like that..
<Button Content="+" x:Name="btnAdd" />
-->
</GridView>
And, how can I add a ADD button(grid item) to XAML? thanks
You can achieve that by using a DataTemplateSelector, basically what you need to do is :
define another class that will represent the GridView "addItem"
public class GridItem
{
public String Subject { get; set; }
public String TargetDate { get; set; }
}
public class AddGridItem : GridItem
{
public bool IsGridItem { get; set; }
}
Make sure that your GridView's ItemSource collection has always an AddGridItem in it
private ObservableCollection<GridItem> _gridItems =new ObservableCollection<GridItem>()
{
new GridItem()
{
Subject = "Subject1",
TargetDate = "TargetDate"
},new GridItem()
{
Subject = "Subject2",
TargetDate = "TargetDate"
},new GridItem()
{
Subject = "Subject3",
TargetDate = "TargetDate"
},new AddGridItem()
{
IsGridItem = true
}
};
public ObservableCollection<GridItem> GridItems
{
get
{
return _gridItems;
}
set
{
if (_gridItems == value)
{
return;
}
_gridItems = value;
}
}
Create a DataTemplateSelector class that will return the appropriate DataTemplate based on the Item type
public class MyDataTemplateSelector : DataTemplateSelector
{
public DataTemplate RegularTemplate { get; set; }
public DataTemplate AddTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item,
DependencyObject container)
{
if (item is AddGridItem)
return AddTemplate;
if (item is GridItem)
return RegularTemplate;
return base.SelectTemplateCore(item, container);
}
}
Define your dataTempaltes and a DataTemplateSelector as staticresources to use them in your GridView
<Page.Resources>
<DataTemplate x:Key="RegularTemplate">
<Grid HorizontalAlignment="Left" Width="250" Height="250">
<Border BorderThickness="3" BorderBrush="White">
<StackPanel VerticalAlignment="Bottom" Background="LightSkyBlue">
<TextBlock Text="{Binding Subject}" Style="{StaticResource BaseTextBlockStyle}" Height="60" Margin="15,0,15,0" FontWeight="SemiBold"/>
<TextBlock Text="{Binding TargetDate}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,15,10" FontSize="12"/>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
<DataTemplate x:Key="AddItemTemplate">
<Border BorderThickness="3" BorderBrush="White" Background="DodgerBlue">
<FontIcon Glyph="" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White"/>
</Border>
</DataTemplate>
<local:MyDataTemplateSelector x:Key="MyDataTemplateSelector"
RegularTemplate="{StaticResource RegularTemplate}"
AddTemplate="{StaticResource AddItemTemplate}">
</local:MyDataTemplateSelector>
</Page.Resources>
<Grid>
<GridView ItemsSource="{Binding GridItems}" ItemTemplateSelector="{StaticResource MyDataTemplateSelector}">
</GridView>
</Grid>

Silverlight- DataGrid control - Selection Changed event interfering with sorting

I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this?
In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way?
Included is my code.
The Page:
<UserControl x:Class="WebServicesApp.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5">
<ContentControl VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5">
<TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" />
<TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/>
<Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/>
</StackPanel>
</ContentControl>
<Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True"
HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200"
ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible">
<data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False"
AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single"
HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged">
<data:DataGrid.Columns>
<data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /> <!--Width="150"-->
<data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /> <!--Width="500"-->
<data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" />
</data:DataGrid.Columns>
</data:DataGrid>
</Grid>
</StackPanel>
<Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed">
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" />
<Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000">
<StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" >
<ContentControl>
<StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal">
<TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" />
<TextBox x:Name="EmailPopupTextBox" Width="200" />
</StackPanel>
</ContentControl>
<ContentControl>
<StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0">
<TextBlock Text="Don't send when update was done by:" />
<StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" >
<TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" />
<Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" >
<Rectangle Fill="White" />
<Border Background="White">
<ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" />
</Border>
</Grid>
</StackPanel>
<Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25">
<Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/>
</Button>
</StackPanel>
</ContentControl>
<TextBlock Text="Where Clause Condition:" />
<TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" />
<ContentControl>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" />
<Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" />
<Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" />
</StackPanel>
<TextBlock x:Name="TestContitionResults" Visibility="Collapsed" />
</StackPanel>
</ContentControl>
</StackPanel>
</Border>
</Grid>
</Grid>
And the call that occurs when the grid's selection is changed:
Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If mFirstTime Then
mFirstTime = False
Else
Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor)
Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing
If IncidentGrid.SelectedItem IsNot Nothing Then
selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor)
EmailPopupTextBox.Text = selectedGridItem.Address
SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID
WhereClauseTextBox.Text = selectedGridItem.whereClause
IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem)
End If
If IncidentGrid.SelectedIndex > -1 Then
EditPersonPopupGrid.Visibility = Windows.Visibility.Visible
Else
EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed
End If
End If
End Sub
Sorry if my code is atrocious, I'm still learning Silverlight.
That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the SelectionChanged event fires twice when you click the column header and to make matters worse, the index of the selected item doesn't stay synched with the currently selected item.
I'd suggest you work your way around it by using the knowledge that the first time SelectionChanged fires, the value of the datagrid's SelectedItem property will be null
Here's some sample code that at least lives with the issue. Your SelectionChanged logic can go in the if clause.
public partial class Page : UserControl
{
private Person _currentSelectedPerson;
public Page()
{
InitializeComponent();
List<Person> persons = new List<Person>();
persons.Add(new Person() { Age = 5, Name = "Tom" });
persons.Add(new Person() { Age = 3, Name = "Lisa" });
persons.Add(new Person() { Age = 4, Name = "Sam" });
dg.ItemsSource = persons;
}
private void SelectionChanged(object sender, EventArgs e)
{
DataGrid grid = sender as DataGrid;
if (grid.SelectedItem != null)
{
_currentSelectedPerson = grid.SelectedItem as Person;
}
else
{
grid.SelectedItem = _currentSelectedPerson;
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Frozen Columns in Silverlight DataGrid..
http://dotnetdreamer.wordpress.com/2009/01/31/silverlight-2-datagrid-frozen-columns/
There's a bugfix for the first issue you mentioned (selection changed event getting fired on resort).
See the following URL for Microsoft's patch:
http://www.microsoft.com/downloads/details.aspx?familyid=084A1BB2-0078-4009-94EE-E659C6409DB0&displaylang=en
This worked, but now if I sort twice, on the first one it sorts, and then does the popup as the first selected item of the grid . If I close the popup grid, and then try to sort a second time, it stack overflows, and crashes firefox out.
I'm thinking I may need to rethink working in silverlight until the system gets a bit more stable.
Thanks for the answer Hovito!