Silverlight TreeViewItem, Binding to IsSelected, how to?
In reading a post about TreeView and binding to a view model (http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx), it seems that binding a TreeViewItem IsSelected property is possible. However, I have the following code which always fails on Initialize() because it's trying to set a read-only property?
<sdk:TreeView Grid.Column="0" Grid.Row="2" Style="{StaticResource TreeViewStyle}"
ItemsSource="{Binding tvData}" >
<sdk:TreeView.ItemContainerStyle>
<Style TargetType="sdk:TreeViewItem">
<Setter Property="IsEnabled" Value="True" />
<Setter Property="IsExpanded" Value="True" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</sdk:TreeView.ItemContainerStyle>
<sdk:TreeView.ItemTemplate>
<sdk:HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ItemName}" FontWeight="{Binding ItemFontWeight}"/>
开发者_运维百科 </StackPanel>
</sdk:HierarchicalDataTemplate>
</sdk:TreeView.ItemTemplate>
You can't assign a binding via a Setter
in a Style
. Effectively what you are doing there is attempting to set a binding on the Setter.Value
property. Xaml doesn't infer that you mean to set a binding on the target property. In turn the Setter
just assumes you are trying to set a value directly to IsSelected
which it knows is read only hence the error.
I can recommend this technique for getting around the problem:
http://blogs.msdn.com/b/delay/archive/2009/05/07/one-more-platform-difference-more-or-less-tamed-settervaluebindinghelper-makes-silverlight-setters-better.aspx
EDIT: I should mention that I have not tried the technique for this exact scenario (binding the IsSelected property of a TreeViewItem), but I have used it on numerous other occasions, and so far it has worked flawlessly.
精彩评论