所以,我正在尝试对我拥有的自定义组件执行一些数据绑定,但我似乎无法找到有关如何执行此操作的任何有用的信息。我想要做的是让主窗口中的自定义组件具有Bindning属性...
<local:MultiColumnComboBox ItemsSource="{Binding Customers}" x:Name="NewCombo"></local:MultiColumnComboBox>
然后在自定义组件中......
<DataGrid ItemsSource="{Binding ItemsSource}" Name="dataGrid"></DataGrid>
如果有人知道如何做到这一点,我们将不胜感激一些指导:)
修改
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IList<Customer>), typeof(MultiColumnComboBox));
public MultiColumnComboBox()
{
InitializeComponent();
}
//Items Source Binding
public IList<Customer> ItemsSource
{
get
{
return (IList<Customer>)GetValue(ItemsSourceProperty);
}
set
{
System.Console.WriteLine("Binding");
System.Console.WriteLine(value);
SetValue(ItemsSourceProperty, value);
}
}
答案 0 :(得分:0)
当我将错误的ownerType传递给DependencyProperty.Register方法时,我遇到了Binding错误...请检查以确保您使用的是typeof(MultiColumnComboBox),如下所示。
/// <summary>
/// Interaction logic for MultiColumnComboBox.xaml
/// </summary>
public partial class MultiColumnComboBox : UserControl
{
/// <summary>
/// This creates the dependency property for the collection to display.
/// </summary>
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IList<Customer>), typeof(MultiColumnComboBox));
/// <summary>
/// This property gets you to the collection that's being displayed.
/// </summary>
public IList<Customer> ItemsSource
{
get { return (IList<Customer>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public MultiColumnComboBox()
{
InitializeComponent();
}
}
另外,请确保在UserControl中设置Binding ElementName,使其具有正确的DataContext。
<UserControl x:Class="DependencyPropertyExample.MultiColumnComboBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="userControl1">
<Grid>
<DataGrid ItemsSource="{Binding Path=ItemsSource, ElementName=userControl1}" />
</Grid>
</UserControl>
答案 1 :(得分:0)
我已经明白了!
您所要做的就是使用控件中的DataContext属性,以便在主页面中使用..
<local:custom control DataContext="{Binding Something}" />
在你的自定义控件中,我绑定了......
ItemsSource="{Binding DataContext, ElementName=UOMControl}"
就是这样。