gpt4 book ai didi

c# - 如何让我的 View 显示属性?

转载 作者:行者123 更新时间:2023-12-03 10:35:29 28 4
gpt4 key购买 nike

使用 Prism 库,我已经成功地创建了一个工作 View 模型。但是,当我尝试设置任何属性时,它不会显示在 View 中。

在此示例中,方法 OnSumbit 将 Name 设置为“Hello”,但这不会在 View 中显示它。我怎样才能让它显示在 View 中?

class ItemTemplateVM : BindableBase
{
private ItemTemplateModel itemTemplateModel;

public ICommand SubmitCommand { get; private set; }

public ItemTemplateVM()
{
this.SubmitCommand = new DelegateCommand(this.OnSubmit);
this.ItemTemplateModel = new ItemTemplateModel();
}

private void OnSubmit()
{
this.ItemTemplateModel.Name = "Hello";
}

public ItemTemplateModel ItemTemplateModel
{
get { return this.itemTemplateModel; }
set { SetProperty(ref this.itemTemplateModel, value); }
}

XAML
    <TextBox Height="23" TextWrapping="Wrap" Text="{Binding ItemTemplateModel.Entry, Mode=TwoWay}"/>
<TextBox Height="23" TextWrapping="Wrap" Text="{Binding ItemTemplateModel.Name, Mode=TwoWay}"/>
<TextBox Height="23" TextWrapping="Wrap" Text="{Binding ItemTemplateModel.Displayid, Mode=TwoWay}"/>
<Button Content="Button" Command="{Binding SubmitCommand}"/>

最佳答案

您的 xaml 中有三个绑定(bind)

<TextBox Text="{Binding ItemTemplateModel.Entry, Mode=TwoWay}"/>
<TextBox Text="{Binding ItemTemplateModel.Name, Mode=TwoWay}"/>
<TextBox Text="{Binding ItemTemplateModel.Displayid, Mode=TwoWay}"/>

他们三个都直接绑定(bind)到对象 ItemTemplateModel s 属性。由于该类(class)不开火 PropertyChanged View 永远不会收到有关更改的通知,因此,这里最简单的解决方案是制作 ItemTemplateModel继承自 BindableBase然后更改属性,使它们看起来类似于 View 模型,即
...
set { SetProperty(ref this.Entry, value); }
...

另一方面,最好(IMO)直接从 View 模型中公开这些属性,并将模型单独用作数据对象,所以对我来说,更好的解决方案是:
<TextBox Text="{Binding Entry, Mode=TwoWay}"/>
<TextBox Text="{Binding Name, Mode=TwoWay}"/>
<TextBox Text="{Binding Displayid, Mode=TwoWay}"/>

.
class ItemTemplateVM : BindableBase
{
private ItemTemplateModel itemTemplateModel;

...
public ItemTemplateModel ItemTemplateModel
{
get { return this.itemTemplateModel; }
set { SetProperty(ref this.itemTemplateModel, value); }
}

public string Entry {
get { return itemTemplateModel.Entry; }
set {
if (itemTemplateModel.Entry == value)
return;

itemTemplateModel.Entry = value;
RaisePropertyChanged(); // I believe this is the prism variant of firing PropertyChanged
}
}

// same for Name and DisplayId

另外,请注意 WPF 中有一个名为 DataTemplate 的概念。 ,所以名称 ItemTemplateViewModel对于一般的 ViewModel 来说是一个不幸的名字。我相信最好将其命名为 ViewModel,即如果您的 View 被命名为 MyView , 调用 View 模型 MyViewModel

关于c# - 如何让我的 View 显示属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366514/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com