如何将用户控件的属性绑定到WPF中同一控件的属性?

fir*_*fly 2 data-binding wpf

在我的用户控件内,我有一个集合调用解决方案

 public List<string> Solutions { get; set; }
Run Code Online (Sandbox Code Playgroud)

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

我试过了

<ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194" Height="21" VerticalAlignment="Bottom" 
              ItemsSource="{Binding Path=Solutions}"    />
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.

Lar*_*ens 9

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

<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>
Run Code Online (Sandbox Code Playgroud)

如果你想要正确绑定你的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>
Run Code Online (Sandbox Code Playgroud)