如何在XAML中将DataContext设置为静态属性?

时间:2012-04-19 22:50:58

标签: wpf xaml

这对我不起作用

<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

2 个答案:

答案 0 :(得分:4)

简单地DataContext="{x:Static Brushes.Blue}"并将Value="{Binding DataContext}"更改为Value="{Binding}"

当您在绑定表达式中指定路径时,它始终与您的DataContext相关,因此当您使用{Binding DataContext}时,您实际上绑定到DataContext.DataContext,这不是您想要的。

答案 1 :(得分:1)

我想你想要

<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>