簡體   English   中英

將Button.IsEnabled綁定到布爾屬性

[英]Binding Button.IsEnabled to Boolean Property

我有一個布爾屬性,它查看多個復選框,如果選中其中任何一個,則返回true。 如果要選中任何復選框,我想啟用一個按鈕(屬性返回true)。

目前,我有以下內容:

  • 數據上下文集

     public MainWindow() { InitializeComponent(); this.DataContext = this; } 
  • 按鈕綁定集

     <Button Name="button" IsEnabled="{Binding ButtonEnabled}">Apply</Button> 
  • 物業

     public bool ButtonEnabled { get { if(checkboxes_enabled) return true; else return false; } } 

我已經驗證了該屬性正在按預期進行更新,因此將其縮小為一個具有約束力的問題。 我還嘗試了按鈕內的數據觸發器:

<Button Name="button" Content="Apply">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ButtonEnabled}" Value="True">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ButtonEnabled}" Value="False">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

兩件事情:

如果要對綁定的屬性進行更新,則需要INotifyPropertyChanged

public class MyClass
{
    private bool _buttonEnabled;
    public bool ButtonEnabled
    {
        get
        {
            return _buttonEnabled;
        }
        set
        {
            _buttonEnabled = value;
            OnPropertyChanged();
        }
    }

    public SetButtonEnabled()
    {
        ButtonEnabled = checkboxes_enabled;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged<T>([CallerMemberName]string caller = null) 
    {
        var handler = PropertyChanged;
        if (handler != null) 
        {
            handler(this, new PropertyChangedEventArgs(caller));
        }
    }
}

您也不應有兩個觸發器,而應使用默認值。

<Button Name="button" Content="Apply">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="IsEnabled" Value="True"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ButtonEnabled}" Value="False">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

您需要添加以下代碼以實現INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

然后從屬性設置器調用OnPropertyChanged

我建議將按鈕綁定到命令,而不是事件,這樣,您可以將命令的“ canexecute”屬性設置為false並禁用整個命令,該命令將為您自動禁用按鈕。

我建議使用下面的教程,以更好地了解WPF命令以及如何使用它們,一旦您了解了它們的工作原理,我就會發現它們非常有用。

http://www.codeproject.com/Articles/274982/Commands-in-MVVM#hdiw1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM