简体   繁体   中英

Bind IsEnabled to linq property with linq expression

i would like to bind in XAML button's attribute "IsEnabled" to the condition, like "enable button only if all of items in my Observable collection have IsValid property = true". So the Linq expression would look like:

MyObsCollectionProp.Any(record=>!record.IsValid)

or

 MyObsCollectionProp.All(record=>record.IsValid)

Can sombody tell my the legal and valid (for MVVM pattern) way to do this?

Declare a boolean property named IsButtonEnable as:

private bool isButtonEnable;
public bool IsButtonEnable
{
    get
    {
        return isButtonEnable;
    }
    set
    {
        isButtonEnable = value;
        OnPropertyChanged("IsButtonEnable");
    }
}

Bind a button with this property as:

<Button Content="Save Data" IsEnable="{Binding IsButtonEnable, UpdateSourceTrigger=PropertyChanged}"></Button>

Now in your ViewModel bind ObservableCollectionChanged event as:

public MyViewModel()
{
    MyObsCollectionProp = new ObservableCollection<YourModel>();
    MyObsCollectionProp += MyObsCollectionProp_Changed;
}
void MyObsCollectionProp_Changed(object sender, NotifyCollectionChangedEventArgs e)
{
    // Handle here
    IsButtonEnable = MyObsCollectionProp.All(record=>record.IsValid)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM