WPF:将主窗体属性传递给用户控件

标签 wpf binding parameter-passing dependency-properties

我已经设置了自己的用户控件,其中包含两个组合框,每个组合框项源都绑定(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/

相关文章:

WPF 弹出窗口 : how to make a reusable template for popups?

wpf - 居中DatePicker控件

c# - DataGridComboBoxColumn ItemsSource 列表未找到

java - 从 PHP5 调用 Java 方法

绑定(bind)和闭合 groovy

wcf - 如何使用 webinvoke 方法(Post 或 PUT)在 wcf rest 中传递多个 body 参数

c# - 如何消除 RichTextBox 中段落之间的空格?

Silverlight DataGrid.Celltemplate 绑定(bind)到 ViewModel

c - 动态内存访问仅在函数内部有效

c# - C#中按输出和按引用传递参数有什么区别