C# 使用MultiDataTrigger时出现数据绑定问题
它看起来很简单,我尝试了我知道的所有可能的方法来修复错误,但仍然没有运气,看起来我遗漏了一些东西。 这是我的密码。至少是相关部分C# 使用MultiDataTrigger时出现数据绑定问题,c#,wpf,xaml,C#,Wpf,Xaml,它看起来很简单,我尝试了我知道的所有可能的方法来修复错误,但仍然没有运气,看起来我遗漏了一些东西。 这是我的密码。至少是相关部分 <ItemsControl ItemsSource="{Binding Source}" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid/> </It
<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未获取该值
“数字”
如果我移除所有触发器,那么一切都会正常工作。某种程度上,绑定出现了中断。像VisualBrush这样的可自由化对象不属于元素树(既不是逻辑树也不是VisualTree)。因此,您必须获取datacontext并绑定到VisualBrush的Visual属性 假设数字来自ViewModel,请按如下方式更改代码:
<TextBlock Text="{Binding Path=Number}" Width="50" Height="30" Background="White" />
这是因为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();
}
}
<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">
...
...
...
<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>
...
。。。
...