【问题标题】:WPF Binding TextBox Text Property to a specific ViewModel's Property in a TreeViewWPF 将 TextBox 文本属性绑定到 TreeView 中的特定 ViewModel 属性
【发布时间】: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>
                &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}" />

非常感谢。

更新

我发现这是抛出异常,因为 SelectedItem 上的 TwoWay DataBinding 是不允许的。

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

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

    堆栈面板>
    

    像魅力一样工作。

    【讨论】:

    • 谢谢,正是我想要的。
    猜你喜欢
    • 2011-02-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2011-08-26
    • 2012-10-03
    • 2015-01-25
    • 1970-01-01
    相关资源
    最近更新 更多