简体   繁体   中英

XAML -> C# Update a Text property from Resources in C#

I had a TextBlock in Xaml to display a title. I used to set a x:Uid="MyTitle" , describe in a resources file. But now, my title can change. I try to bind on a title variable in my .cs (and we can't bind on ax:Uid).

So ! I try to change my title directly on the C# and... I failed. Here's my idee :

My Tree

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

I find the problem. I just use my key like "Mytitle_1" or "Mytitle_1.Text".

All I needed is that :

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

Voila !

ResourceLoader loader = new ResourceLoader();

private void ChangeTitle()
{
   if (something)
      Exemples.Text = loader.GetString("MyTextInResources1");
   else
      Exemples.Text = loader.GetString("MyTextInResources2");
 }  

and in your resources file donot add .Text to your string, it is only added for xaml controls.

so in your resources file simply add a new row as

MyTextInResources1     your string to be displayed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM