wpf - 如何将用户控件的属性绑定(bind)到 WPF 中同一控件的属性?

标签 wpf data-binding

在我的用户控件中,我有一个集合调用

 public List<string> Solutions { get; set; }

我想将该属性绑定(bind)到同一用户控件的 xaml 中的组合框吗?

我试过
<ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194" Height="21" VerticalAlignment="Bottom" 
              ItemsSource="{Binding Path=Solutions}"    />

但这似乎不起作用。

最佳答案

在 XAML 中命名您的 UserControl 并从绑定(bind)中引用它,如下所示:

<UserControl x:Name = "MyUserControl">
  <ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194"
            Height="21" VerticalAlignment="Bottom" 
            ItemsSource="{Binding ElementName=MyUserControl, Path=Solutions}" />
</UserControl>

如果您想要正确绑定(bind)您的 UserControl 应该为该属性实现 INotifyPropertyChanged 或使该属性成为依赖属性

更新

或者如果您不想命名 UserControl,请使用 RelativeSource
<UserControl>
  <ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194"
            Height="21" VerticalAlignment="Bottom" 
            ItemsSource="{Binding Path=Solutions, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</UserControl>

关于wpf - 如何将用户控件的属性绑定(bind)到 WPF 中同一控件的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1933650/

相关文章:

c# - 自定义面板内的项目未正确排列

c# - 从类访问 MainWindow 变量

c# - WPF:将列表动态绑定(bind)到(某些)对象的属性

javascript - Polymer Templatizer 实例和主机之间的数据绑定(bind)

c# - 创建图像的缩略图并将它们存储在缓存中

wpf - WPF中的自定义文字包装

使用 RenderTargetBitmap 的 WPF 内存泄漏?

.net - 如何将底层对象绑定(bind)到控件?

c# - WPF/XAML/MVVM - 根据条件设置复选框的状态

c# - WPF TextBox 数据绑定(bind)问题 > :-(