开发者

Initializing static resource from code in C# WPF app

I have two WPF windows. Main one contains a grid bound to ObservableCollection&l开发者_如何学Ct;Person>. I can add and remove objects (people) from the list. I also have another window that I can show when I modify a person.

Person has three properties: Name, LastName and Age and properly implements INotifyPropertyChanged. In the new window I have 3 textboxes that are bound to a static resource Person called "person".

When I initialize new window I provide Person object to the constructor and then I want this person properties to be shown in the three textboxes.

When the code below looks like this everything works properly:

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;  
}  

However I prefer doing it like this:

public ModifyPerson(Person modPerson)  
{  
    // ... some code  
    this.Resources["person"] = modPerson;  
}

But then it does not work. (The resource is assigned properly, but the textboxes do not present the values of modPerson properties.

How can that be solved?


Person is your model object. Instead of using as a StaticResource place it in a property that you bind to.

public ModifyPerson(Person modPerson)
{
    personToModify = modPerson;
}

private Person personToModify;

public Person PersonToModify
{
    get
    {
        return personToModify;
    }
}

And XAML:

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

(I left out labels in order to be concise)

You could use DynamicResource instead of StaticResource but using either of those for your Model really isn't their intended purpose and instead you should use a Binding.


Try to use DynamicResource instead of StaticResource


in XAML:

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

in Code: u need a copy for UI binding, like this,

public EditPlayerWindow(PlayerBO arg)
        : this() {
        this.source =arg;
        this.view = new PlayerBO();
        arg.CopyTo(this.view);
        this.DataContext = view;
    }

the CopyTo like:

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;

}

At last:

view.CopyTo(source);

then save source.

May it helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜