如何绑定XAML中观测值的属性



我有一个chatroomviewmodel:

//ObservableObject implements INotifyPropertyChanged
public class ChatroomViewModel : ObservableObject
{
    private ObservableCollection<Chat> _chatCollection;
    public ObservableCollection<Chat> ChatCollection
    {
        get { return this._chatCollection;  }
        set
        {
            if (null != value)
            {
                this._chatCollection = value;
                OnPropertyChanged("ChatCollection");
            }
        }
    }
}

chatroomview:

<ListBox Grid.Row="1" ItemsSource="{Binding ChatCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="Name: "/>
                <TextBlock Text="{Binding ChatCollection.Name}"/>
                <TextBlock Text="Created by: "/>
                <TextBlock Text="{Binding ChatCollection.CreatedBy}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这是Chatmodel:

//ObservableDatabaseModel also implements INotifyPropertyChanged
public class Chat : ObservableDatabaseModel
{
    private string _name;
    public string Name 
    {
        get { return this._name; }
        set
        {
            this._name = value;
            base.OnPropertyChanged("Name");
        }
    }
    private string _createdBy;        
    public string CreatedBy 
    {
        get { return this._createdBy; }
        set
        {
            this._createdBy = value;
            base.OnPropertyChanged("CreatedBy");
        }
    }
}

绑定起作用,但它只是显示对象的位置,而不是指定的名称/createby属性文本。

我不知道为什么它不起作用,我使用了ObservableCollection<Chat>,而不是List<Chat>,因为它也可以绑定其属性,我还实现了InotifyPropertychangange,将其实现为"子类":

我不使用任何额外的MVVM框架,所以我无法使用MVVM-Light解决方案或类似的方法做很多事情。

ListBoxItem s内的UI元素的DataContext已经是您的Chat类的实例。

wpf自动分配了ListBoxItemDataContext及其所有内容,将其所有内容分配给 data项目的相应实例。。

因此,您的绑定应该像这样:

<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Created by: "/>
<TextBlock Text="{Binding CreatedBy}"/>

数据模板中的数据上下文是项目。

尝试以下操作:

<ListBox Grid.Row="1" ItemsSource="{Binding ChatCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="Name: "/>
                <TextBlock Text="{Binding Name}"/>
                <TextBlock Text="Created by: "/>
                <TextBlock Text="{Binding CreatedBy}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</List

请注意,我删除了" ChatCollection"。从绑定。

最新更新