在C# WPF应用程序中从代码初始化静态资源

3
我有两个WPF窗口。主窗口包含一个绑定到ObservableCollection<Person>的表格。 我可以向列表中添加和删除对象(人)。 我还有另一个窗口,当我修改一个人时可以显示。
人具有三个属性:Name,LastName和Age,并且正确实现INotifyPropertyChanged。 在新窗口中,我有3个文本框,它们绑定到名为“person”的静态资源Person。
当我初始化新窗口时,我向构造函数提供Person对象,然后我希望这个人的属性显示在三个文本框中。
当下面的代码如下所示时,一切正常:
public ModifyPerson(Person modPerson)  
{  
    // ... some code  
    Person p = this.Resources["person"] as Person;  
    p.Name = modPerson.Name;  
    p.LastName = modPerson.LastName;  
    p.Age = modPerson.Age;  
}  

然而,我更喜欢像这样做:
public ModifyPerson(Person modPerson)  
{  
    // ... some code  
    this.Resources["person"] = modPerson;  
}

但是它却无法正常工作。(资源已正确分配,但文本框未显示modPerson属性的值。)
该如何解决?

你能展示一下你的文本框是如何定义的吗? - CodeNaked
你确定已经调用了NotifyPropertyChanged吗? - Brian Liang
你为什么要使用StaticResource - McAden
3个回答

1
人是您的“模型”对象。不要将其作为“静态资源”使用,而是将其放置在属性中,以便进行绑定。
public ModifyPerson(Person modPerson)
{
    personToModify = modPerson;
}

private Person personToModify;

public Person PersonToModify
{
    get
    {
        return personToModify;
    }
}

还有XAML:

<StackPanel DataContext="{Binding PersonToModify}">
    <TextBox Text="{Binding Name, Mode=TwoWay" />
    <TextBox Text="{Binding LastName, Mode=TwoWay" />
    <TextBox Text="{Binding Age, Mode=TwoWay" />
</StackPanel>

为了简洁起见,我省略了标签。

您可以使用DynamicResource代替StaticResource,但是对于您的Model,使用任何一种都不是它们的预期目的,而应改用Binding


0

在XAML中:

<TextBox Text="{Binding Name}"></TextBox>
<TextBox Text="{Binding LastName}"></TextBox>
<TextBox Text="{Binding Age}"></TextBox>

在代码中: 你需要一个用于UI绑定的副本,就像这样,
public EditPlayerWindow(PlayerBO arg)
        : this() {
        this.source =arg;
        this.view = new PlayerBO();
        arg.CopyTo(this.view);
        this.DataContext = view;
    }

类似于CopyTo:

public void CopyTo(PlayerBO player) {
player.Id = this.Id;
player.Name = this.Name;
player.CurrentPolicyVersion = this.CurrentPolicyVersion;
player.CreatedAt = this.CreatedAt;
player.UpdatedAt = this.UpdatedAt;
player.Description = this.Description;
player.MACAddress = this.MACAddress;
player.IPAddress = this.IPAddress;
player.Policy = Policy;

}

最后:

view.CopyTo(source);

然后保存源代码。

希望能有所帮助!


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接