Tristan Read
Tristan Read

Reputation: 61

How to get a string from c# code to XAML (WPF)

I am trying to get a string from my C# code over to my XAML, but I can't seem to find a way to do it

My C# code

public string demoColour= "#FFFFFF";

My XAML Code

...
<Trigger Property="IsMouseOver" Value="True">
    <Setter Property="Background" TargetName="Bd" Value="{ NOT SURE WHAT GOES HERE :( }"/>
</Trigger>                            
...

Upvotes: 0

Views: 820

Answers (1)

Warsox
Warsox

Reputation: 63

As Clemes said, you should take a look at data binding. Data binding is one really important thing in WPF.

But here is one Solution, which works fine:

  1. Make a new Class called ViewModel
  2. Add a Property to that Class like public string MyColor { get; set; } = "#FFFFFF";
  3. Set the DataContext in your XAML:
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
  1. Bind your Property to your XAML whereever you want. For Example:
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="{Binding MyColor}"/>
        </Style>
    </Window.Resources>

Upvotes: 2

Related Questions