I am trying to find how to bind an int variable as my value in style. Here is my simple xaml style.
<Style TargetType="Button" x:Key="ButtonMenu">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="White"/>
</Style>
In the fourth row, I wanna change the value from 14 to my variable called SizeVar bud I can't find how to do it. I really tried googling but can't find anything that works for me. I know that I should do it somehow through binding but not exactly how.
I tried using different binding options but couldn't find one that works for me. My English is also not perfect so maybe it is possible that I misunderstood something.
CodePudding user response:
From your description I interpreted the following:
- You have a XAML-file where in the Resources you want to contain a style called "ButtonMenu".
- The variable that binds to the FontSize is called "SizeVar" and is contained in the DataContext, which is set.
With this, I tested it out and the following works.
In the View (XAML):
...
<Window.DataContext>
<viewmodels:MainViewModel/>
</Window.DataContext>
<Window.Resources>
<Style TargetType="Button" x:Key="ButtonMenu">
<Setter Property="FontSize" Value="{Binding SizeVar}"/>
</Style>
</Window.Resources>
<Grid>
<Button
Content="Test"
Style="{DynamicResource ButtonMenu}"/>
</Grid>
...
In the associated ViewModel (C#):
private int _sizeVar;
public int SizeVar
{
get => _sizeVar;
set
{
_sizeVar = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
SizeVar = 14;
}