Reputation: 115
What is the proper way to define an object to use in both .cs and .xaml files? For example, I have a custom color and brush defined in my "constants.cs" class:
using System.Windows.Media;
namespace MyProject
{
public static class Constants
{
public static Color MyBlue = Color.FromArgb(255, 35, 97, 146);
public static SolidColorBrush MyBlueBrush = new SolidColorBrush(MyBlue);
}
}
and I want to use MyBlue or MyBlueBrush in either .xaml or .cs files.
I can get to the color in .cs files like this:
namespace MyProject
{
public partial class MyColorWindow : Window
{
public MyColorWindow()
{
InitializeComponent();
btnOne.Background = Constants.MyBlueBrush;
}
}
}
But how do I get to it in the XAML file? For example, what do I add to the code below to access MyBlueBrush?
<Window x:Class="MyProject.MyColorWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MyColorWindow" Height="300" Width="300">
<Grid>
<Button Name="btnOne" Background="Purple" Margin="0,32,0,185" />
<Button Name="btnTwo" Background="Orange" Margin="0,132,0,85" /> <!-- I want this background to be MyBlueBrush too -->
</Grid>
</Window>
Upvotes: 3
Views: 2958
Reputation: 564811
You can only bind to properties, not to fields.
In order to bind from XAML, you will need to convert the static members to properties.
Once you do that, you can bind to them via the x:Static Markup Extension, ie:
<Button Name="btnTwo"
Background="{x:Static my:Constants.MyBlueBrush}"
Margin="0,132,0,85" />
(Note that this requires an xmlns mapping for the "MyProject" namespace to "my", as well.)
Upvotes: 5