问题
In WinRT App (C#) I have List<Item> items, which bind to ListBox.Class Item has 2 fields: string Name and bool IsSelected. As you already understood, I want to bind IsSelected field to IsSelected Property of ListBoxItem.
Why I need this? Why I didn't use SelectedItems property of my ListBox?
- When
ListBoxjust loaded, I already have some Items, which must beIsSelected = true - I don't want to create another collection to store all selected items.
What I'm looking for?
I'm looking for elegant solution, like in WPF:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
But we all know, that WinRT doesn't support bindings in setters at all.
I also check nice post in Filip Skakun blog - and this is one of solution, but I need to write some of the BindingBuilder/BindingHelper by my self.
And now, I know two way to solve my problem:
- Bind
SelectedItemsproperty ofListBoxand store another collection of items. - I do not like this way - Do it like Filip Skakun - if I find nothing I use this.
In ideal situation I want to use native solution for this, or maybe someone already wrote/tested nested BindingBuilder for my situation - it's will be helpful too.
回答1:
How about creating a derived ListBox:
public class MyListBox : ListBox
{
protected override void PrepareContainerForItemOverride(
DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
if (item is Item)
{
var binding = new Binding
{
Source = item,
Path = new PropertyPath("IsSelected"),
Mode = BindingMode.TwoWay
};
((ListBoxItem)element).SetBinding(ListBoxItem.IsSelectedProperty, binding);
}
}
}
来源:https://stackoverflow.com/questions/17184517/bind-isselected-property-of-listboxitem-in-listbox-with-multiple-selection-mode