Jon Erickson
Jon Erickson

Reputation: 114866

How do you set a DataContext to a Static property in XAML?

This isn't working for me

<UserControl x:Class="BenchmarkPlus.PMT.UI.Views.Circle"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" x:Name="root"
             DataContext="{Binding Source={x:Static Brushes.Blue}}">
    <UserControl.Resources>
        <Style TargetType="Ellipse">
            <Setter Property="Fill" Value="{Binding DataContext}" />
        </Style>
    </UserControl.Resources>
    <Grid>
        <Ellipse Stroke="Black"></Ellipse>
    </Grid>
</UserControl>

enter image description here

Upvotes: 1

Views: 3231

Answers (2)

Bob Vale
Bob Vale

Reputation: 18474

I think you want

<UserControl x:Class="BenchmarkPlus.PMT.UI.Views.Circle" 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" x:Name="root" 
             DataContext="{x:Static Brushes.Blue}"> 
    <UserControl.Resources> 
        <Style TargetType="Ellipse"> 
            <Setter Property="Fill" Value="{Binding}" /> 
        </Style> 
    </UserControl.Resources> 
    <Grid> 
        <Ellipse Stroke="Black"></Ellipse> 
    </Grid> 
</UserControl> 

Upvotes: 1

Adi Lester
Adi Lester

Reputation: 25201

Make it simply DataContext="{x:Static Brushes.Blue}" and change Value="{Binding DataContext}" to Value="{Binding}".

When you specify a path in your binding expression, it's always relative to your DataContext, so when you use {Binding DataContext}, you're actually binding to DataContext.DataContext, which isn't what you want.

Upvotes: 5

Related Questions