我有一个转换器,它接受一个 bool 值,并根据它的真假返回 A 或 B。转换器根据布尔值选择正确的值,但仅在开始时,如果我在运行时更改布尔值,转换器不会更新。
基本上,我有一个用户控件,其中有一个按钮,该按钮切换“IsOpen”属性,这有效。但我有一个多重绑定器,它将 IsOpen 绑定到(按钮的)图像,它将根据 IsOpen 切换图像。但它不更新,只保留开始时的值。 (IsOpen 确实会在单击时切换,这不是问题)
我的用户控件,我在其中进行多重绑定:
<v:IconButton ColorPalette="{StaticResource MilkySolid}" ColorPaletteFore="{StaticResource BlackToBrightPalette}" IconMargin="0" Content="" VerticalAlignment="Top" Margin="0" HorizontalAlignment="Left" FontSize="1" Height="26" IconWidth="26" Click="IconButton_Click">
<v:IconButton.Image>
<MultiBinding Converter="{StaticResource AorBConverter}">
<Binding Path="IsOpen"/>
<Binding Source="{StaticResource collapseBTN}"/>
<Binding Source="{StaticResource expandBTN}"/>
</MultiBinding>
</v:IconButton.Image>
</v:IconButton>
CodeBehind(这部分有效)
private void IconButton_Click(object sender, RoutedEventArgs e)
{
IsOpen = !IsOpen;
}
public bool IsOpen
{
get { return (bool)GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register("IsOpen", typeof(bool),
typeof(ParamNodeV), new PropertyMetadata(false));
用户控件的视图模型(这也有效)
public bool IsOpen
{
get { return isOpen; }
set
{
isOpen = value;
OnPropertyChanged(nameof(IsOpen));
}
}
所以,就像我说的,转换器根据布尔值选择正确的图像。但如果我在运行时更新 bool 值,它不会更新。
如果您问我为什么我不只是使用触发器:我正在尝试从我的 UserControl (ParamNodeV) 更改 CustomControl (IconButton) 上的图像,并且我不知道如何访问 IconButton 的属性ParamNodeV,无需完全覆盖样式/模板。因此,如果有人帮助我使用转换器,或者帮助我如何从 UserControl 导航到 IconButton 的 Image 属性,而无需覆盖样式/模板
表情
<Binding Path="IsOpen"/>
将当前DataContext作为源对象。
在后面的代码中,您显然正在更改 UserControl 的 IsOpen 属性 - 这应该是一个不同的对象。
因此,Binding 应使用该属性作为源,即使用 UserControl 作为源对象:
<Binding Path="IsOpen" RelativeSource="{RelativeSource AncestorType=UserControl}"/>