我正在尝试用自定义控件替换 ListView DataTemplate 中的标准控件,但绑定似乎无法正常工作。下面是 ListView 的定义:
<Grid>
<ListView ItemsSource="{Binding DataItemsCollection}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Static text" />
<TextBlock Text="{Binding DataItemText}" />
<BindingTest:CustomControl CustomText="{Binding DataItemText}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
其中 DataItemsCollection 是一个可观察的类型集合
public class DataItemClass : INotifyPropertyChanged
{
string _dataItemText;
public string DataItemText
{
get { return _dataItemText; }
set { _dataItemText = value; Notify("DataItemText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void Notify(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
主窗口代码如下所示:
public partial class MainWindow : Window
{
public ObservableCollection<DataItemClass> _dataItemsCollection = new ObservableCollection<DataItemClass>
{
new DataItemClass { DataItemText = "Test one" },
new DataItemClass { DataItemText = "Test two" },
new DataItemClass { DataItemText = "Test three" }
};
public ObservableCollection<DataItemClass> DataItemsCollection
{
get { return _dataItemsCollection; }
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
}
自定义控件很简单:
<StackPanel Orientation="Horizontal">
<Label Content="Data Item:" />
<TextBlock Text="{Binding CustomText, Mode=OneWay}" />
</StackPanel>
将 CustomText 定义为
public static DependencyProperty CustomTextProperty = DependencyProperty.Register(
"CustomText", typeof(string), typeof(CustomControl), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string CustomText
{
get { return (string)GetValue(CustomTextProperty); }
set { SetValue(CustomTextProperty, value); }
}
当我运行这个项目时,我在 DataTemplate 的第二个 TextBlock 中看到了正确的文本,但在自定义控件中却没有。我究竟做错了什么?