【发布时间】: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