【发布时间】:2011-04-29 22:10:30
【问题描述】:
我有一个 TreeView,我已绑定到一个名为 RootViewModel 的 ViewModel,它有一个 ViewModel 集合 ChildViewModel,它有一个 ViewModel 集合 GrandhChildViewModel。
我在树视图旁边有一个文本框。
我想仅在树中选择GrandChildViewModel 时将文本框的文本绑定到所选项目的特定属性。如果未选择 GrandChildViewModel,我希望文本框中的文本为空。我也想要它,所以如果我在选择 GrandChild 时更改 TextBox 中的文本,它将更新树视图中该项目的文本。 (我假设 viewmodeltextbox 和 viewmodeltreeview
示例视图模型:
public class RootViewModel : INotifyPropertyChanged
{
public ObservableCollection<ChildViewModel> Children{ get; set; }
public bool IsSelected{ get { /* code */ } set { /* code */ OnPropertyChanged("IsSelected"); }
}
public class ChildViewModel : INotifyPropertyChanged
{
public ObservableCollection<GrandChildViewModel> GrandChildren{ get; set; }
public bool IsSelected{ get { /* code */ } set { /* code */ OnPropertyChanged("IsSelected"); }
public string SomeProperty{ get { /* code */ } set { /* code */ OnPropertyChanged("SomeProperty"); }
}
public class GrandChildViewModel : INotifyPropertyChanged
{
public bool IsSelected{ get { /* code */ } set { /* code */ OnPropertyChanged("IsSelected"); }
public bool SomeOtherProperty{ get { /* code */ } set { /* code */ OnPropertyChanged("SomeOtherProperty"); }
}
到目前为止,我在 Xaml 中的尝试:
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<Binding Converter="{StaticResource myConverter}" ElementName="myTreeView" Path="SelectedItem" Mode="TwoWay" />
</DataTrigger.Binding>
<DataTrigger.Setters>
<Setter Property="Text" Value="{Binding Path=SomeOtherProperty}" />
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
也试过了
<TextBox Text={Binding ElementName=myTreeView, Path=SelectedItem, Converter={StaticResource myConverter}, Mode=TwoWay}" />
非常感谢。
更新
我发现这是抛出异常,因为 SelectedItem 上的 TwoWay DataBinding 是不允许的。
【问题讨论】: