【发布时间】:2013-12-04 00:05:16
【问题描述】:
我正在开发一个自定义控件。我希望它支持数据绑定,因此它与内置控件一样易于维护。
这是我目前得到的:
-
包含我的控件的窗口 Window.xaml 代码:
<custom:Matrix x:Name="customMatrix" DockPanel.Dock="Top" Title="{Binding Title}"/> -
... 及其 Window.xaml.cs 代码隐藏(只是视图模型的一个片段)
public ViewModel VM { get; private set; } private ProblemManager() { VM = new ViewModel(); InitializeComponent(); DataContext = VM; VM.Title = "a title"; } public class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public ViewModel() { ItemsList = new ObservableCollection<List<int>>(); } public ObservableCollection<List<int>> ItemsList { get; set; } protected string title; public string Title { get { return title; } set { if (title != value) { title = value; NotifyPropertyChanged("Title"); } } } protected void NotifyPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } -
我的控件 Matrix.xaml
// ... <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Title}"/> // ... -
以及控件的 Matrix.xaml.cs 代码隐藏
public partial class Matrix : UserControl { public Matrix() { InitializeComponent(); DataContext = this; } public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(Matrix), new PropertyMetadata("", TitleChanged)); public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } private void TitleChanged(string title) { Title = title; } private static void TitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((Matrix)d).TitleChanged((string)e.NewValue); } }
问题是,如果不在我的窗口 xaml 中绑定到 Matrix.Title 属性,即在 xaml 中静态地赋予该值,如 Title="some title",我的控制代码中的绑定有效(我什至可以在我的窗口中执行 customMatrix.Title += "1";它有效)。但是,当绑定到Matrix.Title 属性时(就像我在提供的代码中所做的那样),它不起作用,并且我的视图中出现了一个空白标题。只是为了清楚地说明,绑定到窗口中的默认控件是有效的。
如何使 Matrix.Title 属性可绑定?
【问题讨论】:
标签: wpf data-binding wpf-controls custom-controls