WPF:具有依赖属性和子控件的UserControl

时间:2014-08-15 19:24:48

标签: c# wpf xaml combobox user-controls

我正在尝试在WPF中创建自己的,非常简单的Usercontrol。它基本上只是一个Combobox,还有一些额外的逻辑。 我尝试使用本教程创建自己的Depdency-Property:http://www.codeproject.com/Articles/140620/WPF-Tutorial-Dependency-Property

到目前为止这个工作正常,但如果属性发生变化,我也想在用户控件的Combobox中反映出来。看起来我无法将子控件直接绑定到我的新Dependency-Project。

我的代码目前看起来像这样:

public partial class ClassSelector : UserControl
{
    public static readonly DependencyProperty CurrentValueProperty =
 DependencyProperty.Register("CurrentValue", typeof(ClassType),
 typeof(ClassSelector), new FrameworkPropertyMetadata());

    public ClassType CurrentValue
    {
        get
        {
            return  (ClassType)this.GetValue(CurrentValueProperty);
        }
        set
        {
            this.SetValue(CurrentValueProperty, value);
        }
    }

    public ClassSelector()
    {
        this.DataContext = this;
        InitializeComponent();
        cmbClassType.ItemsSource = Enum.GetValues(typeof(ClassType));
    }
}

设置dependy-property或Combobox的值对我来说似乎很奇怪。 我试图通过以下方法将它绑定在xaml中:

<Grid>
    <ComboBox x:Name="cmbClassType" SelectedItem="{Binding Path=CurrentValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectionChanged="cmbClassType_SelectionChanged" />
</Grid>

我尝试使用组合框映射Dependicy-Project已更改事件,反之亦然,但这会导致非常奇怪的代码,因为组合框更改必须更改属性值和属性值组合框。

我很确定必须有可能将DependencyProperty绑定到子控件,但我找不到一种方法来使其工作。

提前感谢所有建议的人,祝周末愉快

的Matthias

Edith说:调用Window需要将Object绑定到Grid,而不是绑定到Window,例如:

grdMain.DataContext = new DeckSearch();

工作正常,同时

this.DataContext = new DeckSearch();

此行为仅在我的自定义控件上,所有其他控件与Window本身的DataContext完美配合。

1 个答案:

答案 0 :(得分:1)

好的,所以我在这里修复了你的代码,它在我的最后工作

UserControlCodeBehind

public partial class ClassSelector : UserControl
{
    public static readonly DependencyProperty CurrentValueProperty = DependencyProperty.Register("CurrentValue", typeof(ClassType),
        typeof(ClassSelector), new FrameworkPropertyMetadata()
            {
                DefaultValue = ClassType.Type1,
                BindsTwoWayByDefault = true,
                PropertyChangedCallback = CurrentValueChanged,
                DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });


    private static void CurrentValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var obj = (ClassSelector)d;
        obj.cmbClassType.SelectedValue = e.NewValue;
    }

    public ClassType CurrentValue
    {
        get
        {
            return (ClassType)this.GetValue(CurrentValueProperty);
        }
        set
        {
            this.SetValue(CurrentValueProperty, value);
        }
    }

    public ClassSelector()
    {
        InitializeComponent();
        cmbClassType.ItemsSource = Enum.GetValues(typeof(ClassType));
        cmbClassType.SelectedValue = CurrentValue;
    }

}

UserControl的Xaml部分

<Grid>
    <ComboBox x:Name="cmbClassType" SelectedValue="{Binding Path=CurrentValue}"/>
</Grid>

请检查它是否在您的最后工作。我没有添加任何额外的代码检查线程安全和所有。

修改

在我的解决方案中,当Class更改时,我会收到Property CurrentValue次通知。

以下是我的示例MainWindow代码。

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        Task.Run(() =>
            {
                Thread.Sleep(1000);
                Dispatcher.InvokeAsync(() =>
                    {
                        customCombobox.CurrentValue = ClassType.Type3;//Updating the UserControl DP
                    });
                Thread.Sleep(2000);
                this.CurrentValue = ClassType.Type2;//Updating my local Property
            });
    }

    private ClassType _currentValue;
    public ClassType CurrentValue
    {
        get { return _currentValue; }
        set
        {
            _currentValue = value;
            Debug.WriteLine("Value Changed to " + value.ToString());
            RaisePropertyChanged("CurrentValue");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void RaisePropertyChanged(string propName)
    {
        var pc = PropertyChanged;
        if (pc != null)
            pc(this, new PropertyChangedEventArgs(propName));
    }
}

我的MainWindow.xaml

<Window x:Class="WpfApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication"
    Title="MainWindow" Height="250" Width="525">
<local:ClassSelector x:Name="customCombobox" Height="25" CurrentValue="{Binding CurrentValue}"/>
</Window>