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

时间:2009-12-19 17:52:00

标签: wpf data-binding

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

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

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

我试过

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

但这似乎不起作用。

2 个答案:

答案 0 :(得分: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>

如果你想要正确绑定你的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>

答案 1 :(得分:2)

将控件的XAML移动到Template属性,即代替

<UserControl x:Class="MyUserControl" ...>
    ...
    <ComboBox ... />
    ...
</UserControl>

使用

<UserControl x:Class="MyUserControl" ...>
    <UserControl.Template>
        <ControlTemplate>
            ...
            <ComboBox ... />
            ...
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

然后,您可以使用TemplateBinding

            <ComboBox ... ItemsSource="{TemplateBinding Solutions}" />
顺便说一下,你的问题与这个问题非常相似:Custom UserControl Property used by child element