我已经设置了自己的用户控件,其中包含两个组合框,每个组合框项源都绑定(bind)到一个 DependencyProperty。我遇到的问题是将属性从使用我的用户控件的表单传递给用户控件。
下面是我的用户控件:
public static readonly DependencyProperty ListOneProperty = DependencyProperty.Register
("ListOne", typeof(List<int>), typeof(LinkedComboBox), new PropertyMetadata(new List<int>()));
public List<int> ListOne
{
get { return (List<int>)GetValue(ListOneProperty); }
set { SetValue(ListOneProperty, value); }
}
public static readonly DependencyProperty ListTwoProperty = DependencyProperty.Register
("ListTwo", typeof(List<string>), typeof(LinkedComboBox), new PropertyMetadata(new List<string>()));
public List<string> ListTwo
{
get { return (List<string>)GetValue(ListTwoProperty); }
set { SetValue(ListTwoProperty, value); }
}
public LinkedComboBox()
{
InitializeComponent();
FillListOne();
}
下面是我的 MainWindow xaml:
<control:LinkedComboBox x:Name="LinkedBox" ListTwo="{Binding MyList}"/>
和MainWindow.xaml.cs:
static List<string> _myList = new List<string>{"abc","efg"};
public List<string> MyList
{
get { return _myList; }
set { _myList = value; }
}
public MainWindow()
{
InitializeComponent();
}
我需要什么才能让用户控件接受来自主窗口的绑定(bind)?
最佳答案
一切都很好,只是您需要一个 PropertyChangedCallback
来处理您的属性。
这是一个简单的例子
public static readonly DependencyProperty ListTwoProperty = DependencyProperty.Register
("ListTwo", typeof(List<string>), typeof(LinkedComboBox), new PropertyMetadata(new List<string>(), new PropertyChangedCallback(Changed)));
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//e.NewValue here is your MyList in MainWindow.
}
关于WPF:将主窗体属性传递给用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14302638/