它看起来很简单,我尝试了所有可能的方法,我知道修复错误仍然没有运气,看起来像是错过了什么。 这是我的代码。至少相关部分
<ItemsControl ItemsSource="{Binding Source}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<VirtualizingStackPanel Orientation="Horizontal">
<ContentControl>
<Path x:Name="Bound" Stroke="Black">
<Path.Style>
<Style>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Condition1}"
Value="true"/>
<Condition Binding="{Binding Condition2}"
Value="false"/>
</MultiDataTrigger.Conditions>
<Setter Property="Path.Data">
<Setter.Value>
<RectangleGeometry Rect="{Binding Rect1}"/>
</Setter.Value>
</Setter>
<Setter Property="Path.Fill">
<Setter.Value>
<VisualBrush>
<VisualBrush.Visual>
// Here is the Problem
<TextBlock Text="{Binding Number}"
Width="50"
Height="30"
Background="White" />
// Binding is not working
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Path.Style>
</Path>
</ContentControl>
</VirtualizingStackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
visualBrush中的TextBlock未获取值
'数字'
如果我删除所有触发器,那么一切正常。不知何故,绑定中断了。
答案 0 :(得分:1)
那是因为VisualBrush没有DataContext。你必须使用一些代理元素。
定义代理元素:
public class DataContextProxy: Freezable
{
public DataContextProxy()
{
BindingOperations.SetBinding(this, DataContextProperty, new Binding());
}
public object DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
public static readonly DependencyProperty DataContextProperty = FrameworkElement
.DataContextProperty.AddOwner(typeof (DataContextProxy));
protected override Freezable CreateInstanceCore()
{
return new DataContextProxy();
}
}
将其添加到具有您需要的DataContext的父资源中:
<ItemsControl ItemsSource="{Binding Source}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<VirtualizingStackPanel Orientation="Horizontal">
<ContentControl>
<ContentControl.Resources>
<behavior:DataContextProxy x:Key="Proxy"
DataContext="{Binding}" />
</ContentControl.Resources>
<Path x:Name="Bound" Stroke="Black">
...
然后将TextBlock的DataContext绑定到代理的DataContext:
...
<Setter Property="Path.Fill">
<Setter.Value>
<VisualBrush>
<VisualBrush.Visual>
<TextBlock DataContext="{Binding Source={StaticResource Proxy},
Path=DataContext}"
Text="{Binding Number}"
Width="50"
Height="30"
Background="White" />
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
...
Haven没有亲自尝试过,但是应该工作......评论一下是不是!
干杯。
答案 1 :(得分:0)
像FreeBrush这样的Freezable对象不是元素树的一部分(逻辑树或VisualTree都不是。所以你必须得到datacontext并绑定到VisualBrush的Visual Property。
假设number来自ViewModel更改您的代码如下:
<TextBlock Text="{Binding Path=Number}" Width="50" Height="30" Background="White" />