【问题标题】:XAML -> C# Update a Text property from Resources in C#XAML -> C# 从 C# 中的资源更新文本属性
【发布时间】:2015-03-31 11:54:14
【问题描述】:

我在 Xaml 中有一个 TextBlock 来显示标题。我曾经设置一个x:Uid="MyTitle",在资源文件中描述。但是现在,我的头衔可以改变了。我尝试绑定我的 .cs 中的标题变量(我们无法绑定 x:Uid)。

所以!我尝试直接在 C# 上更改我的标题并且...我失败了。 这是我的想法:

我的树

Root
 Source
  -code.xaml
  -code.xaml.cs
 Resources
  En
   -resources.resw
     "Mytitle_1.Text", "This is my first title"
     "Mytitle_2.Text", "This is the other one"

code.xaml

<TextBlock TextWrapping="Wrap" x:Name="Exemples" FontSize="20" Margin="20, 0, 20, 0" LineHeight="25" MaxLines="2" FontFamily="Segoe UI Light" Height="65"/>

code.xaml.cs

private string GetResources(string key)
{
   ResourceLoader rl = ResourceLoader.GetForCurrentView("../Resources");
   string resources = rl.GetString(key);

   return resources;
}

private void ChangeTitle()
{
  if (something)
   Exemples.Text = GetResources("Mytitle_1");
  else
   Exemples.Text = GetResources("Mytitle_2");
}

【问题讨论】:

    标签: c# wpf xaml windows-store-apps windows-8.1


    【解决方案1】:
    ResourceLoader loader = new ResourceLoader();
    
    private void ChangeTitle()
    {
       if (something)
          Exemples.Text = loader.GetString("MyTextInResources1");
       else
          Exemples.Text = loader.GetString("MyTextInResources2");
     }  
    

    并且在您的资源文件中不要将 .Text 添加到您的字符串中,它仅适用于 xaml 控件。

    所以在你的资源文件中 只需添加一个新行作为

    MyTextInResources1     your string to be displayed
    

    【讨论】:

    • 是的!在我的解决方案中,我忘记更改 ResourceLoader loader = new ResourceLoader();我编辑了你的,你错过了一点。
    【解决方案2】:

    我发现了问题。我只是使用“Mytitle_1”或“Mytitle_1.Text”之类的密钥。

    我只需要:

    private string GetResources(string key)
    {
       ResourceLoader rl = ResourceLoader("../Resources");
       string resources = rl.GetString(key);
    
       return resources;
    }
    
    private void ChangeTitle()
    {
       if (something)
       Exemples.Text = GetResources("Mytitle_1/Text");
       else
       Exemples.Text = GetResources("Mytitle_2/text");
    }
    

    瞧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2012-04-02
      相关资源
      最近更新 更多