代码之家  ›  专栏  ›  技术社区  ›  Adam

WPF将TextBox文本属性绑定到树视图中特定ViewModel的属性

  •  2
  • Adam  · 技术社区  · 15 年前

    RootViewModel 它有一组视图模型 ChildViewModel 它有一组视图模型 GrandhChildViewModel .

    我要将文本框的文本绑定到选定项的特定属性 只有 当 GrandChildViewModel 孙子模型 未选中,我希望文本框中的文本为空。我也希望有它,所以如果我改变文本框中的文本时,孙子被选中,它将更新的文本,该项目在树状视图。(我假设viewmodel<->文本框和viewmodel<->treeview之间有双向绑定)

    |------------------|
    | - Root           |
    |   - Child        |     |---------------------------------|
    |     - GrandChild |     | Selected GrandChild's Property  |
    |     - GrandChild |     |---------------------------------|
    |     - GrandChild |                            ^
    |   - Child        |                            |
    |     - GrandChild |<----- Selected GrandChild -|
    |                  |
    |------------------|

    示例视图模型:

    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>
                    &ltDataTrigger 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}" />
    

    更新

    1 回复  |  直到 15 年前
        1
  •  1
  •   Adam    15 年前

    多亏了 this post 我能让它工作。我将文本框周围的StackPanel设置为绑定到所选项目,然后将文本框绑定到我关心的属性。

    <StackPanel DataContext={Binding ElementName=myTreeView, Path=SelectedItem}">
        <TextBox Text={Binding Path=SomeOtherProperty, Mode=TwoWay}" />
    </StackPanel>