I have the following XAML code, where I Bind some data to the listview. Also, I have very important RecipientConverter which allows me to convert my TextBlock. But, here is the problem. This TextBlock must be converter according to the form presented in the TextBlock below (Binding Path=Sum).
So, here is my question, is it possible to send the "Sum" TextBlock as ConverterParameter to the RecipientConverter? I know about MultipleBinding, but this is only suitable for WPF and it is not available in UWP. Maybe here is a way of implementing it with DependencyProperty, but I'm note sure about that.
NOTE:
"Recipient" TextBlock and "Sum" TextBlock are dynamic values which I get from the server.
<ListView x:Name="HistoryList" Padding="10" IsItemClickEnabled="True" Visibility="Collapsed" ItemsSource="{Binding Source={StaticResource TransactionsCVS}}" ItemsPanel="{StaticResource ResourceKey=ItemsPanelTemplate}" ItemClick="HistoryList_ItemClick">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate x:DataType="data:TransactionGroupInfo">
<TextBlock FontWeight="Medium" FontSize="16" Foreground="#999999" Text="{Binding Path=Key}" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:Transaction">
<Grid Height="60" Margin="0,5,0,5" Background="White" CornerRadius="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Background="{Binding Path=VendorAccentColor}" CornerRadius="5,0,0,5" />
<StackPanel VerticalAlignment="Center" Margin="10,0,0,0" Grid.Column="1" Orientation="Vertical">
<TextBlock Text="{Binding Path=VendorName}" FontSize="16" Foreground="#999999" />
<TextBlock Text="{Binding Path=Recipient, Converter={StaticResource RecipientConverter}}" FontSize="16" Foreground="#999999" />
</StackPanel>
<TextBlock Grid.Column="2" Text="{Binding Path=Sum, Converter={StaticResource SumConverter}}" VerticalAlignment="Center" Canvas.ZIndex="2" Margin="0,0,10,0" FontSize="18" FontWeight="Bold" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And here is C# code of my Converter
public object Convert(object value, Type targetType, object parameter, string language)
{
string recipient = (string)value;
// Here is a way I want it to be
string sum = (string)parameter;
if (HalykWallet_v03.Model.AppSettings.GetAppLang() == "ru")
{
if (sum.Contains("-"))
return "На " + recipient;
else
return "От " + recipient;
}
else
{
char[] array = sum.ToCharArray();
if (sum.Contains("-"))
{
switch (array.Last())
{
case '0':
case '1':
case '2':
recipient += recipient + "-ден";
break;
case '3':
case '4':
case '5':
recipient += recipient + "-тен";
break;
case '6':
recipient += recipient + "-дан";
break;
case '7':
case '8':
recipient += recipient + "-ден";
break;
case '9':
recipient += recipient + "-дан";
break;
default:
break;
}
}
else
{
switch (array.Last())
{
case '0':
case '1':
case '2':
recipient += recipient + "-ге";
break;
case '3':
case '4':
case '5':
recipient += recipient + "-ке";
break;
case '6':
recipient += recipient + "-ға";
break;
case '7':
case '8':
recipient += recipient + "-ден";
break;
case '9':
recipient += recipient + "-ға";
break;
}
}
return recipient;
}
}
You can use dependency property in the converter.This should help.
Binding instead of x:bind solved my problem. maybe this will save someone's a day. Here is the link
Hello have you tryed binding it as converter parameter?
<StackPanel VerticalAlignment="Center" Margin="10,0,0,0" Grid.Column="1" Orientation="Vertical">
<TextBlock Text="{Binding Path=VendorName}" FontSize="16" Foreground="#999999" />
<TextBlock Name="txtRecipient" Text="{Binding Path=Recipient, Converter={StaticResource RecipientConverter}}" FontSize="16" Foreground="#999999" />
</StackPanel>
<TextBlock Grid.Column="2" Text="{Binding Path=Sum, Converter={StaticResource SumConverter},ConverterParameter={Binding ElementName=txtrec}}" VerticalAlignment="Center" Canvas.ZIndex="2" Margin="0,0,10,0" FontSize="18" FontWeight="Bold" />
However you can simulate multibinding in UWP with Cimbalino Windows phone toolkit. Have a look at here
Related
how can i display 5 items when we scrolling i want load more.
<ListBox.ItemTemplate>
<DataTemplate >
<Border BorderThickness="0,0,0,1" BorderBrush="Black"
HorizontalAlignment="Stretch" Width="400"
Margin="-8,0,-8,0">
<Grid Height="130"
RenderTransformOrigin="0.37,0.52">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Left"
Height="104"
Grid.Row="0"
VerticalAlignment="Top"
Width="115" Background="White"
Margin="05,-4,0,0">
<Image Source="{Binding company_logo}" Stretch="None"
Margin="10,0,0,0"/>
</Grid>
<Grid Height="104" HorizontalAlignment="Right"
Grid.Row="0"
VerticalAlignment="Top" Width="280"
Background="White" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="307*"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Left"
Margin="0,0,0,0"
TextWrapping="Wrap"
Text="{Binding product_name}"
VerticalAlignment="Top"
FontSize="20"
Foreground="Orange"
Grid.Column="1"/>
<TextBlock Text="Reviews:"
Margin="97.5,27,125,51"
Grid.Column="1"/>
<TextBlock HorizontalAlignment="Left"
Margin="145,30,0,0"
TextWrapping="Wrap"
Text="{Binding product_reviews}"
VerticalAlignment="Top"
FontSize="10" Width="50"
Foreground="Orange"
Grid.Column="1"/>
<TextBlock Text="Rating:" FontSize="15"
Margin="0,25,232,51"
Grid.Column="1"/>
<TextBlock HorizontalAlignment="Left" Margin="50,30,0,0"
TextWrapping="Wrap" Text="{Binding product_rating}"
VerticalAlignment="Top" FontSize="10"
Foreground="Black" Grid.Column="1"/>
<Image Source="Assets/clock-icon.png" Margin="165,25,0,0" Width="25" Height="25"/>
<TextBlock Text="Created Date" FontSize="10"
Margin="155,29,70,62" Foreground="Red"
Grid.Column="1"/>
<TextBlock HorizontalAlignment="Left" Width="59"
Margin="218,29,0,0"
TextWrapping="Wrap"
Text="{Binding created_date}"
VerticalAlignment="Top" FontSize="10"
Foreground="Black"
Grid.Column="1" Height="13">
</TextBlock>
<TextBlock Text="Updated Date:" FontSize="10"
Margin="155,39,70,52" Foreground="Red"
Grid.Column="1"/>
<TextBlock HorizontalAlignment="Left" Width="59"
Margin="218,39,0,0"
TextWrapping="Wrap"
Text="{Binding updated_date}"
VerticalAlignment="Top" FontSize="10"
Foreground="Black"
Grid.Column="1" Height="13">
</TextBlock>
<TextBlock HorizontalAlignment="Left" Margin="3,58,0,0" TextWrapping="Wrap"
Text="{Binding product_description}"
VerticalAlignment="Top" FontSize="10"
Foreground="Black" Height="40"
Width="293" Grid.Column="1" />
</Grid>
<TextBlock HorizontalAlignment="Left" Margin="15,100,0,0"
TextWrapping="Wrap" Width="250"
Text="{Binding companyName}"
VerticalAlignment="Top" FontSize="15"
Foreground="Black"/>
<Button Content="Contact" Foreground="Red"
FontSize="10"
Margin="120,88,-29,440.667"
Height="25" Grid.Column="1"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and my code is below
List<products> products1 = new List<products>();
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("something");
var url = "data/getProductsData";
Parameters product = new Parameters();
product.user_id = "1";
product.platform = "Android";
string json = JsonConvert.SerializeObject(product);
StringContent queryString = new StringContent(json);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync(url, queryString);
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync();
Response my = JsonConvert.DeserializeObject<ResponseWrapper>(data.Result.ToString()).response;
LoadingBar.IsEnabled = true;
LoadingBar.Visibility = Visibility.Visible;
var myData =data.Result.ToString();
//await new MessageDiaglog("Data Loaded!").ShowAsync();
LoadingBar.IsEnabled = false;
LoadingBar.Visibility = Visibility.Collapsed;
foreach (var item in my.content.products)
{
products1.Add(item);
}
}
lstbox.ItemsSource = products1;
}
}
catch (Exception ex)
{
MessageDialog message = new MessageDialog(ex.Message);
message.ShowAsync();
first of all :
1- change this line
List<products> products1 = new List<products>();
with this
public static ObservableCollection<products> products1 = new ObservableCollection<products>();
2- get scrolling postion of your listbox
public static ScrollViewer GetScrollViewer(DependencyObject dpj)
{
if (dpj is ScrollViewer) return dpj as ScrollViewer;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dpj); i++)
{
var child = VisualTreeHelper.GetChild(dpj, i);
var result = GetScrollViewer(child);
if (result != null)
{
return result;
}
}
return null;
}
3- create a handler of listbox_loaded.
private void lstsource_Loaded(object sender, RoutedEventArgs e)
{
ScrollViewer viewer = GetScrollViewer(this.lstsource);
viewer.ViewChanged += lstSoucrce_ViewChanged;
}
4- on view changed ...
private async void lstSoucrce_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
var sv = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.lstsource, 0), 0);
var verticaloffset = sv.VerticalOffset;
var maxVerticleOffset = sv.ScrollableHeight;
if (maxVerticleOffset < 0 || verticaloffset == maxVerticleOffset)
{
//this will fired up when you will reach end of list
//load your more data here
}
I want to select the list item when I click the button(Which is inside the list box for every row).
Now I have try like this:-
<ListBox Height="444"
ItemsSource="{Binding StudentDetails,Mode=TwoWay}"
HorizontalAlignment="Left" Margin="2,34,0,0"
Name="listBox1" VerticalAlignment="Top"
Width="476" BorderBrush="#00410D0D"
SelectedIndex="{Binding MemberPrivacy,Mode=TwoWay}"
SelectedItem="{Binding SelectedStudent, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" Padding="5" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Wheat" BorderThickness="1">
<Image Name="ListPersonImage" Source="{Binding PersonImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,0,0,0"/>
</Border>
<TextBlock Text="{Binding FirstName}" Name="firstName" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<Image Height="50" Source="{Binding addImage}" HorizontalAlignment="Left" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="50" />
<Button Margin="-100,0,0,0" Height="80" Width="80" DataContext="{Binding DataContext, ElementName=listBox1}" Command="{Binding addPerson}" >
<Button.Background>
<ImageBrush ImageSource="{Binding addImage, Converter={StaticResource pathToImageConverter}}" Stretch="Fill" />
</Button.Background>
</Button>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My View Model:-
public ListBoxEventsViewModel()
{
addPerson = new ReactiveAsyncCommand();
addPerson.Subscribe(x =>
{
MessageBox.Show("Test Button Selected..");
});
}
Here I can show the message box when I click the button. But I can not select the list item. Please let me know to solve this problem.
Thanks in advance.
View Model:-
List box selected Item:-
public ListBoxEventsModel _SelectedStudent;
public ListBoxEventsModel SelectedStudent
{
get { return _SelectedStudent; }
set
{
this.RaiseAndSetIfChanged(x => x.SelectedStudent, value);
MessageBox.Show("Selected index==>" + SelectedStudent.FirstName);
}
}
Here it showing the selected name when I click the list item. But this same thing I want to write it for the button(addImage)
Bind the SelectedItem on the ListBox to a "SelectedItem" property on the ViewModel.
eg SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
then on the view model just add a property of SelectedItem, then you can just set that from in your subscribe.
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.
I have a grid view with the following Group Style Header template:
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="1,0,0,6">
<Button
AutomationProperties.Name="Group Title"
Command="{Binding GroupCommand}"
Style="{StaticResource TextPrimaryButtonStyle}"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}" Margin="3,-7,10,10" Style="{StaticResource GroupHeaderTextStyle}" />
<TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource GroupHeaderTextStyle}"/>
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
The problem is that when I click the button, the GroupCommand does not execute.
What can be the problem here ?
you should try this way:
private void Button_Tapped_1(object sender, TappedRoutedEventArgs e)
{
SampleDataItem item = new SampleDataItem("test", "test!", "subtitle", "", "", "", null);
SampleDataSource.AddItemToFirstGroup(item);
}
private void Button_Tapped_2(object sender, TappedRoutedEventArgs e)
{
SampleDataGroup group = new SampleDataGroup("test", "testGroup", "subtitle", "", "");
group.Items.Add(new SampleDataItem("test", "test!", "subtitle", "", "", "", null));
SampleDataSource.AddGroup(group);
}
I got it from here
WinRT (Win 8) Store App XAML Bindings RelativeSourceMode FindAncestor missing?
I wanted to bind my button to an ICommand in my ViewModel, so I did it like this:
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="1,0,0,6">
<Button
AutomationProperties.Name="Group Title"
Command="{Binding ElementName=myParentGridView, Path=DataContext.GroupCommand}"
Style="{StaticResource TextPrimaryButtonStyle}"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}" Margin="3,-7,10,10" Style="{StaticResource GroupHeaderTextStyle}" />
<TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource GroupHeaderTextStyle}"/>
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
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!