XAML 中的 WPF 图像可见性绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20188787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Image Visibility Binding in XAML
提问by Constantin Treiber
I've got a little problem binding an image to a Radiobuttion. I only want to bind it via XAML an what I did is this.. I createad a Stackpanel with 5 radiobutton in it..
我在将图像绑定到 Radiobuttion 时遇到了一个小问题。我只想通过 XAML 绑定它,我所做的就是这个。我创建了一个包含 5 个单选按钮的 Stackpanel。
<StackPanel Name="StackPanel1" Grid.Row="3" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<RadioButton GroupName="Group1" Content="1"
HorizontalAlignment="Left"
Width="35" BorderThickness="1,0,0,1"
IsChecked="CodeBehindBinding..." />
<RadioButton GroupName="Group1" Content="2"
HorizontalAlignment="Left" VerticalAlignment="Top"
Width="35" BorderThickness="1,0,0,1"
IsChecked="{CodeBehindBinding..." />
......
Somewhere else in the XAML i tryied to bind a Label to the group. Together..
在 XAML 的其他地方,我尝试将标签绑定到组。一起..
<Image Grid.Row="3" Grid.Column="2" HorizontalAlignment="Left" Height="25" VerticalAlignment="Top" Width="25" Source="/*****;component/Resources/Checked.png"
Visibility="{Binding IsChecked, BindingGroupName=StackPanel1.Group1}"
/>
...Nothinig happens. ;-) The Image is permanent visibile.
……什么都没发生。;-) 图像是永久可见的。
How can I fix it ? Hope you can help .. Greetz Iki
我该如何解决?希望你能帮忙.. Greetz Iki
回答by Ofir
I assume that "IsChecked" property is Boolean. In order to bind Visibilityproperty you must bind to Visibility type property or use converter.
我假设“IsChecked”属性是布尔值。为了绑定Visibility属性,您必须绑定到 Visibility 类型属性或使用转换器。
If you don't want to use converter you need to declare Visibility notification property:
如果您不想使用转换器,则需要声明 Visibility 通知属性:
private Visibility isChecked= Visibility.Visible;
public Visibility IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
RaisePropertyChanged("IsChecked");
}
}
If you want to stay with your Boolean parameter, use Visibility converter
如果您想保留布尔参数,请使用 可见性转换器
回答by Clemens
Two things wrong here. First, you need to assign a Nameto the RadioButton you want to use as binding source and use that for the binding's ElementNameproperty.
这里有两件事不对。首先,您需要将 a 分配给Name要用作绑定源的 RadioButton,并将其用于绑定的ElementName属性。
<RadioButton x:Name="radioButton1" ... />
Then your binding also needs a converter from boolto Visibility. You could use WPF's BooleanToVisibilityConverter:
然后您的绑定还需要一个转换器从bool到Visibility。您可以使用 WPF 的BooleanToVisibilityConverter:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>radia
<Image Visibility="{Binding IsChecked, ElementName=radioButton1,
Converter={StaticResource BooleanToVisibilityConverter}}" ... />

