what wrong with my binding convert?
I have radiobutton and I want to define binding between the radiobutton.IsChecked state and the visibility some stackpanel so I wrote this convert method:
public class RadioBtnState2Visible : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
开发者_开发知识库return ( bool )value == true ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
return ( Visibility )value == Visibility.Visible ? true : false;
}
}
And I make the binding - The xaml:
<local:PageEx.Resources>
<local:RadioBtnState2Visible x:Key="Convert" />
</local:PageEx.Resources>
<RadioButton x:Name="MyRadioBtn1" GroupName="group1" />
<RadioButton x:Name="MyRadioBtn2" GroupName="group1" />
<StackPanel Visibility="{Binding ElementName=MyRadioBtn1, Path=IsChecked, Converter={StaticResource Convert}}" />
But nothing works!
The visibility state of the stackpanel is always Visible!
What I did wrong?
Got your code working with one minor change. I made the converter a page resource:
<UserControl.Resources>
<local:RadioBtnState2Visible x:Key="Convert" />
</UserControl.Resources>
I should also mention that I had to actually put something in the stackpanel as well to see the change as by default it collapses to nothing :) I assume you actually have content in your real stackpanel.
Just to explain what is happening here. By adding "local:" to the resource declaration you are actually enclosing an instance of a Resource, and not changing the current resource. Referencing it by "Convert" does not work because it cannot find the resource where it expects to find it.
Is this Silverlight or WPF? You might need to specify the Mode for the Binding. Mode=OneWay should work.
In fact, RadioButon.IsChecked is not a bool
but a Nullable<bool>
1
So, your code should be :
public class RadioBtnState2Visible : IValueConverter
{
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
return (value == true) ? Visibility.Visible : Visibility.Collapsed; // the explicit check to true is needed because of case value=null
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
return value == Visibility.Visible ; // yup, it's a boolean
}
}
It should work better.
精彩评论