本文介绍了如何将用户控件的属性与WPF中同一个控件的属性进行绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的用户控件内我有一个收集呼叫解决方案
public List< string>解决方案{get;组;我想将该属性绑定到同一用户控件的xaml中的组合框中?
>
我尝试过
< ComboBox HorizontalAlignment =LeftMargin =21 ,0,0,41Name =cbAddSolutionWidth =194Height =21VerticalAlignment =Bottom
ItemsSource ={Binding Path = Solutions}/>
但似乎不起作用。
解决方案在XAML中命名您的UserControl,并从绑定中引用它,如下所示:
< UserControl x:Name =MyUserControl>
< ComboBox HorizontalAlignment =LeftMargin =21,0,0,41Name =cbAddSolutionWidth =194
Height =21VerticalAlignment =Bottom
ItemsSource ={Binding ElementName = MyUserControl,Path = Solutions}/>
< / UserControl>
如果你想要正确绑定,你的UserControl应该为该属性实现INotifyPropertyChanged,或者使该属性为依赖属性
更新
或者如果您不想命名UserControl,请使用RelativeSource
< UserControl>
< ComboBox HorizontalAlignment =LeftMargin =21,0,0,41Name =cbAddSolutionWidth =194
Height =21VerticalAlignment =Bottom
ItemsSource ={Binding Path = Solutions,RelativeSource = {RelativeSource AncestorType = {x:Type UserControl}}}/>
< / UserControl>
Inside my user control I have a collection call Solutions
public List<string> Solutions { get; set; }
I want to bind that property to a combobox in xaml of that same user control?
I tried
<ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194" Height="21" VerticalAlignment="Bottom"
ItemsSource="{Binding Path=Solutions}" />
but that didn't seem to work.
解决方案 Name your UserControl in XAML and refer to it from the binding like so:
<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>
If you want proper binding your UserControl should implement INotifyPropertyChanged for that property or make that property a Dependency Property
Update
Or use RelativeSource if you don't want to name the UserControl
<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中同一个控件的属性进行绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!