Let's say I have a ListBox which binds to stuff in code-behind:
<ListBox x:Name="list">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem Content="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox x:Name="name" Text="{Binding ElementName=list, Path=SelectedItem.Name, Mode=TwoWay" />
<TextBox x:Name="contents" Text="{Binding ElementName=list, Path=SelectedItem.Contents, Mode=TwoWay" />
Code behind:
public class Dude
{
public String Name { get; set; }
public String Contents { get; set; }
}
Now the above does just what I want it to. When an item in the listbox is selected, The textboxes update to show what was selected in the listbox.
But what I am now trying to do is expand on my Dude class by adding a Dictionary to it:
public class Dude
{
public string Name { get; set; }
public string Contents { get; set; }
public Dictionary<String, String> Tasks { get; set; }
}
In the hopes that I can:
Click an Item in the ListBox, have the corresponding item's Name and Contents properties display in their respective TextBoxes and then Append to the contents textbox the Key/Value of the Dictionary's contents.
But I don't know how I can go that deep. It kinda feels like I'm going multiple levels, would something like Multidimensional binding be what I need?
Are there any (simple) samples you have, or have seen? Docs, articles, tutorials?
Any help is much appreciated.
Thank you
What you want can be done in WPF (bit harder in other XAML technologies like Wp7 or WinRT), but I'm not sure it's what you need...
Use MultiBinding, to bind both the Contents string and the Tasks dictionary to the second textbox, then write your own IMultiValueConverter to build the string you want to display.
Read the tutorial about MultiBindings here, and the rough code should look something like this:
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{StaticResource YourAppendingConverter}">
<Binding ElementName="list" Path="SelectedItem.Contents" />
<Binding ElementName="list" Path="SelectedItem.Tasks" />
</MultiBinding>
</TextBox.Text>
</TextBox>
and your converter should resemble:
public class YourAppendingConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter,
System.Globalization.CultureInfo culture){
StringBuilder sb = new StringBuilder(values[0].ToString());
sb.AppendLine("Tasks:");
foreach (var task in (Dictionary<string,string>)values[1]){
sb.AppendLine(string.Format("{0}: {1}", task.Key, task.Value));
}
return sb.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
System.Globalization.CultureInfo culture){
throw new NotSupportedException();
}
Why do I think this is what you need?
If you think these through, then MultiBinding might be the tool you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With