【发布时间】:2017-06-06 14:52:18
【问题描述】:
我正在处理一个“简单”的案例。我喜欢创建一个实现 DependencyProperty 的新自定义控件。在下一步中,我想创建一个绑定来更新两个方向的属性。我为此案例构建了一个简单的示例,但绑定似乎不起作用。我找到了一种使用 FrameworkPropertyMetadata 更新 DPControl 属性的方法,但我不知道使用 OnPropertyChanged 事件是否也是一个好主意。
这里是我的示例项目:
我的控件只包含一个标签
<UserControl x:Class="WPF_MVVM_ListBoxMultiSelection.DPControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPF_MVVM_ListBoxMultiSelection"
mc:Ignorable="d" Height="84.062" Width="159.641">
<Grid Margin="0,0,229,268">
<Label Content="TEST" x:Name="label" Margin="0,0,-221,-102"/>
</Grid>
</UserControl>
并实现自定义依赖属性。目前,我还为 FramePropertyMetadata 实现了 PropertyChanged 方法,并在该方法中设置了标签的内容,但我喜欢让它双向工作。
public partial class DPControl : UserControl
{
public DPControl()
{
InitializeComponent();
}
public string MyCustomLabelContent
{
get { return (string)GetValue(MyCustomLabelContentProperty);}
set
{
SetValue(MyCustomLabelContentProperty, value);
}
}
private static void OnMyCustomLabelContentPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
DPControl control = (DPControl)source;
control.label.Content = e.NewValue;
}
public static readonly DependencyProperty MyCustomLabelContentProperty = DependencyProperty.Register(
"MyCustomLabelContent",
typeof(string),
typeof(DPControl),
new FrameworkPropertyMetadata(null,
OnMyCustomLabelContentPropertyChanged
)
);
我只是在一个窗口中使用这个控件:
<local:DPControl MyCustomLabelContent="{Binding MyLabelContent, Mode=TwoWay}" Margin="72,201,286,34"/>
MyLabelContent 是 ViewModel 中的一个属性,它也实现了 INotifyPropertyChanged 接口。
public class ViewModel_MainWindow:NotifyPropertyChanged
{
private string _myLabelContent;
public string MyLabelContent
{
get { return _myLabelContent; }
set { _myLabelContent = value;
RaisePropertyChanged();
}
}...
那么我怎样才能让它工作:在自定义属性上使用绑定功能和我的新控件。
【问题讨论】:
标签: c# wpf data-binding dependency-properties