小编Igo*_*huk的帖子

在DataTemplate中使用自定义控件时,绑定不起作用

我正在尝试用自定义控件替换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>
Run Code Online (Sandbox Code Playgroud)

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

主窗口代码如下所示:

public partial class MainWindow : Window
{
    public ObservableCollection<DataItemClass> …
Run Code Online (Sandbox Code Playgroud)

data-binding wpf custom-controls datatemplate

2
推荐指数
1
解决办法
3551
查看次数

标签 统计

custom-controls ×1

data-binding ×1

datatemplate ×1

wpf ×1