【问题标题】:Initializing static resource from code in C# WPF app从 C# WPF 应用程序中的代码初始化静态资源
【发布时间】:2014-03-10 15:43:40
【问题描述】:

我有两个 WPF 窗口。主要的包含一个绑定到ObservableCollection<Person> 的网格。我可以从列表中添加和删除对象(人)。当我修改一个人时,我还有另一个窗口可以显示。

Person 具有三个属性:Name、LastName 和 Age,并正确实现了 INotifyPropertyChanged。在新窗口中,我有 3 个文本框绑定到名为“person”的静态资源 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 属性的值。

如何解决?

【问题讨论】:

  • 你能说明你的文本框是如何定义的吗?
  • 你确定你 NotifyPropertyChanged 了吗?
  • 你为什么要使用StaticResource

标签: c# wpf initialization resourcedictionary


【解决方案1】:

Person 是您的 model 对象。不要将其用作StaticResource,而是将其放在您绑定到的属性中。

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

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      在 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);
      

      然后保存源代码。

      愿它有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        • 2022-12-04
        • 2010-11-26
        • 2019-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多