将wpf对象属性绑定到类属性 - 通常的方式对我不起作用

时间:2014-04-14 06:35:54

标签: c# wpf xaml binding code-behind

! 嗨,大家好。我有一个问题=( 这样的约束(就像示例中的所有地方和这里的答案一样)在我的案例中不起作用:

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"。 其他一切都还可以,因为这段代码填充了#34; TextBlock"与"名称" (添加 Text = _configVM.name ):

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

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

1 个答案:

答案 0 :(得分:0)

给出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>