如何将控件IsEnabled属性绑定到某个计数器

时间:2011-03-08 22:53:52

标签: binding

我想只在我的计数器达到某个数字(比如1)

时启用一些按钮
int questionCounter;
public int QuestionCounter
{
    get { return questionCounter; }
    set 
    { 
        questionCounter = value;
        if (questionCounter == 1)
            OnPropertyChanged(new PropertyChangedEventArgs("IsEnabled"));
    }
}

<Button Style="{DynamicResource GoBackButton}"
    x:Name="GoBack" Click="GoBack_Click" Margin="100,10,0,0" 
            IsEnabled="{Binding IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type Window}, Mode=FindAncestor}}" >

,初始按钮状态为:

{button.IsEnabled = False;}

但我在这里没有成功......

任何帮助,请

1 个答案:

答案 0 :(得分:3)

我建议绑定到转换器的结果

public class IsEnabledConverter : IValueConverter
{

    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Convert.ToBoolean(Convert.ToInt32(value) > 0);
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

并像这样绑定

<Window.Resources>
    <local:IsEnabledConverter x:Key="isEnabledConverter"></local:IsEnabledConverter >
</Window.Resources>

[...]

<Button Style="{StaticResource GoBackButton}"
    x:Name="GoBack" Click="GoBack_Click" Margin="100,10,0,0" 
            IsEnabled="{Binding IsEnabled,  Converter={StaticResource isEnabledConverter}}" />