我试图用自定义控件替换 ListView DataTemplate 内的标准控件,但绑定(bind)似乎无法正常工作。这是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>
自定义文本定义为
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 中看到正确的文本,但在自定义控件内部却看不到。我做错了什么?
最佳答案
默认Binding
相对于 DataContext
,即DataItemClass
在你的情况下,但是 CustomText
属性(property)声明于 CustomControl
。您需要指定相对绑定(bind)源:
<TextBlock Text="{Binding Path=CustomText,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=BindingTest:CustomControl}}" />
如果您的控件要保持那么简单,您可以完全删除 CustomText
属性(property)和变化<TextBlock Text="{Binding CustomText, Mode=OneWay}" />
到只是<TextBlock Text="{Binding DataItemText} />
.
关于wpf - 在 DataTemplate 中使用自定义控件时绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14047869/