【问题标题】:binding to a property of an object绑定到对象的属性
【发布时间】:2013-03-14 16:52:12
【问题描述】:

我想将网格中的 一系列文本框绑定对象的属性中,该对象本身就是我的 ViewModel 中的另一个属性(数据上下文)。

CurrentPersonNameAge 属性组成

ViewModel 内部:

public Person CurrentPerson { get; set ... (with OnPropertyChanged)}

Xaml:

<TextBox Text="{Binding Name}" >
<TextBox Text="{Binding Age}" >

我不确定使用方法,我在网格范围内设置了另一个 DataContext,没有任何结果,还尝试再次设置源和路径,如 Source=CurrentPerson,Path=Age 没有任何结果,这些是为了试试看会不会有变化。

我应该如何做到这一点?

【问题讨论】:

    标签: c# wpf mvvm binding


    【解决方案1】:

    试试这个:

    <TextBox Text="{Binding CurrentPerson.Name}" />
    <TextBox Text="{Binding CurrentPerson.Age}" />
    

    基本上,您可以使用. 分隔符深入了解属性。

    为了将来参考,如果您想深入了解集合,可以像在代码中一样使用MyCollection[x](其中 x 将替换为硬编码数字,不是变量)。

    【讨论】:

    • +1 并感谢您提供的信息,不确定在 Xaml 部分中我是否可以使用它,但我想我也尝试过这种方式。再次执行此方法没有结果,CurrentPerson 定义并触发 NotifyPropertyChanged,但可能缺少一些东西。
    • 似乎通知更改不会以这种方式采取行动。是真的吗?我该如何解决这个问题?
    • 确保足够早地创建对象(即在构造函数中)
    【解决方案2】:

    你的Person班级成员NameAge自己养INPC吗?

    如果您想更新ViewModelNameAge 的值并使其反映在视图中,您还需要它们在Person 类中单独提出更改的属性。

    绑定没问题,但是视图模型的更改不会通知视图。还要记住UpdateSourceTriggerTextBox 默认为LostFocus,因此将其设置为PropertyChanged 将在您输入时更新ViewModel 中的字符串。

    简单示例:

    public class Person : INotifyPropertyChanged {
      private string _name;
      public string Name {
        get {
          return _name;
        }
    
        set {
          if (value == _name)
            return;
    
          _name = value;
          OnPropertyChanged(() => Name);
        }
      }
    
      // Similarly for Age ...
    }
    

    现在您的 xaml 将是:

    <StackPanel DataContext="{Binding CurrentPerson}">
      <TextBox Text="{Binding Name}" />
      <TextBox Margin="15"
                Text="{Binding Age}" />
    </StackPanel>
    

    或者您也可以按照@Kshitij 的建议进行绑定:

    <StackPanel>
      <TextBox Text="{Binding CurrentPerson.Name}" />
      <TextBox Margin="15"
                Text="{Binding CurrentPerson.Age}" />
    </StackPanel>
    

    并在您输入时更新视图模型:

    <StackPanel DataContext="{Binding CurrentPerson}">
      <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
      <TextBox Margin="15"
                Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 2011-10-03
      • 2020-04-01
      • 1970-01-01
      相关资源
      最近更新 更多