2013-01-13 46 views
2

我已经建立了自己的用户控件,它包含两个组合框,每个组合框项目源都绑定到一个DependencyProperty。我遇到的问题是将使用我的用户控件的表单传递给用户控件。WPF:将主窗体属性传递给用户控件

下面是我的用户控件:

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(); 
    } 

而下面是我的主窗口的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(); 

    } 

我需要做什么来让用户控件接受来自主窗口的绑定?

+0

你不应该那样做从MAINVIEW,但你NEET使用INotifyPropertyChanged的http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does -a-better-way-exist – ZSH

+0

为什么我不应该从MainView那么做?如果我拥有的列表是在主窗体中创建的,那么我应该如何获得这个控件?我是新来的WPF一般,所以任何提示将不胜感激。 –

+0

如果您刚刚开始,在获得一些知识之后,您可能想要学习像MVVM(或MVP或MVC)这样的模式,以便更好地掌握事情的真正工作方式,而不是将所有数据放在主视图中并将其绑定,谷歌mvvm,你可以得到很多的例子 – ZSH

回答

2

一切都很好,除了你需要一个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. 
} 
+0

现在就试试这个,谢谢。 –

相关问题