【问题标题】:Binding wpf object property to class property - usual way doesnt work for me将 wpf 对象属性绑定到类属性 - 通常的方法对我不起作用
【发布时间】:2014-04-14 16:48:29
【问题描述】:

! 嗨,大家好。我有问题=( 这样的绑定(就像这里的示例和答案中的任何地方一样)在我的情况下不起作用:

Binding b = new Binding("MyTextPath");
b.Source = YourDataClass;
b.Mode = BindingMode.TwoWay; 
myTextBox.SetBinding(TextBox.TextProperty, b);

所以,我有一个我的类“ConfigVM”的实例“_configVM”,它有一个属性“name”。需要将此属性绑定到“TextBlock.Text”。这是我的代码:

  Binding _textBinding = new Binding("name");
  _textBinding.Source = _configVM;
  _textBinding.Mode = BindingMode.TwoWay;
  TextBlock _textBlockUI = new TextBlock() { Style = (Style)Application.Current.MainWindow.Resources["treeTextBlock"] };
  _textBlockUI.SetBinding(TextBlock.TextProperty, _textBinding);

或其他选项:

  Binding _textBinding = new Binding();
  _textBinding.Source = _configVM;
  _textBinding.Mode = BindingMode.TwoWay;
  _textBinding.Path = new PropertyPath("name");
  TextBlock _textBlockUI = new TextBlock() { Style = (Style)Application.Current.MainWindow.Resources["treeTextBlock"] };
  _textBlockUI.SetBinding(TextBlock.TextProperty, _textBinding);

两者都不起作用,我得到空白的“TextBlock”。 其他一切都很好,因为这段代码用“名称”填充“TextBlock”(添加 Text = _configVM.name):

  TextBlock _textBlockUI = new TextBlock() { Text = _configVM.name, Style = (Style)Application.Current.MainWindow.Resources["treeTextBlock"] };
  _textBlockUI.SetBinding(TextBlock.TextProperty, _textBinding);

但我需要在 TwoWay 模式下绑定,而不仅仅是在编译时赋值

【问题讨论】:

  • 为什么不使用 xaml?
  • 查看调试输出窗口。是否存在绑定错误?
  • 我相信 textblock 文本属性不能以两种方式绑定,也许你想要的是文本框
  • 有动态创建的实例列表。因此不可能在 xaml 中绑定,不是吗?
  • Text = _configVM.name 并不能证明它是一个属性。表达式也可以使用公共字段。

标签: c# wpf xaml binding code-behind


【解决方案1】:

给定一个ConfigVM

public class ConfigVM
{
    public string Name { get; set; }
}

也许还有一个主视图模型,比如

public class MainVM
{
    public ObservableCollection<ConfigVM> ConfigItems { get; set; }
}

您可以像这样在 XAML 中轻松创建 ItemsControl:

<ItemsControl ItemsSource="{Binding ConfigItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

【讨论】:

  • 嗯,就是这样!适用于 { get; set; }Name,但没有它们就无法工作。我应该在整个开始时列出该课程的清单。谢谢你,例如ItemTemplate,这样做似乎比后面的代码更好更容易。
  • 没有{ get; set; } 它不是一个属性,而只是一个字段。绑定仅适用于属性。
猜你喜欢
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多