我正在尝试用自定义控件替换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中看到了正确的文本,但是在自定义控件中没有。我做错了什么?
答案 0 :(得分:5)
默认情况下,Binding
相对于DataContext
,在您的情况下为DataItemClass
,但CustomText
属性在CustomControl
中声明。您需要指定相对绑定源:
<TextBlock Text="{Binding Path=CustomText,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=BindingTest:CustomControl}}" />
如果您的控件保持这么简单,您可以完全删除CustomText
属性并将<TextBlock Text="{Binding CustomText, Mode=OneWay}" />
更改为<TextBlock Text="{Binding DataItemText} />
。