2

我正在尝试用自定义控件替换 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 中看到了正确的文本,但在自定义控件中却没有。我究竟做错了什么?

4

1 回答 1

5

默认情况下Binding是相对于DataContextDataItemClass在您的情况下,但CustomText属性是在 中声明的CustomControl。您需要指定相对绑定源:

<TextBlock Text="{Binding Path=CustomText,
                          RelativeSource={RelativeSource Mode=FindAncestor,
                                    AncestorType=BindingTest:CustomControl}}" />

如果您的控件保持如此简单,您可以完全删除CustomText属性并更改<TextBlock Text="{Binding CustomText, Mode=OneWay}" />为 just <TextBlock Text="{Binding DataItemText} />

于 2012-12-27T00:22:45.450 回答