Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing static resource from code in C# WPF app

I have two WPF windows. Main one contains a grid bound to ObservableCollection<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?

like image 959
Michal Avatar asked Jun 06 '26 12:06

Michal


1 Answers

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.

like image 158
McAden Avatar answered Jun 09 '26 02:06

McAden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!