2017-06-05 98 views
1

我有下面的按钮,它的IsEnabled属性绑定到ViewModel中的一个名为EnableBtn的布尔。MVVM将IsEnabled绑定到ViewModel中的多个布尔值

如果我有另一个名为EnableMail的布尔,我将如何修改这个以便IsEnabled绑定到两者?

<Button IsEnabled="{Binding EnableBtn, Converter={StaticResource InvertBooleanConverter}}" x:Name="SaveSendButton" Grid.Row="0" Grid.Column="1" Text="{i18n:Translate SaveAndSend}" Style="{StaticResource bottomButtonsBlue}" Command="{Binding EmailPlanCommand}"></Button> 
+5

绑定到一个属性,该属性返回两个bools的逻辑AND? – Stuart

+1

斯塔特所说的是正确的回应.'EnableBtn'明确地涉及按钮的启用。所以如果需要的话,那个属性的getter也应该考虑EnableMail的值。 – Skintkingle

+0

如果我正确地选择了你,不需要多重绑定,只需绑定一个布尔值并评估get中的所有内容? – DarkW1nter

回答

5
public bool IsBothEnabled 
    { 
     get 
     { 
      if (EnableBtn && EnableMail) 
       return true; 
      return false; 
     } 
    } 

立即绑定Button.IsEnabled物业IsBothEnabled。

+2

请注意,如果其中一个属性EnableBtn或EnableMail发生更改,则必须调用PropertyChanged(“IsBothEnabled”)。 – JanDotNet

+1

不要忘记'EnableBtn'和'EnableMail'的setter应该像往常一样为它们自己引发'PropertyChanged'事件,** AND **复合属性'IsBothEnabled'。 –

+1

'返回EnableBtn && EnableMail'而不是'if'。 –

2

替代从毫克当量的有效的解决方案,你可以使用一个multi binding

的XAML代码如下所示:

<Button.IsEnabled> 
    <MultiBinding Converter="{StaticResource AreAllTrueMultiValueConverter}"> 
     <Binding Path="EnableBtn" /> 
     <Binding Path="EnableMail" /> 
    </MultiBinding> 
</TextBox.IsEnabled> 

然而,你需要类似MultiValueConverter:

public class AreAllTrueMultiValueConverter: IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, 
      object parameter, System.Globalization.CultureInfo culture) 
    { 
     return values.OfType<bool>().All(); 
    } 
    public object[] ConvertBack(object value, Type[] targetTypes, 
      object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotSupportedException("Cannot convert back"); 
    } 
} 

我更喜欢MultiBinding额外的视图模型属性,因为它不需要“依赖属性”,必须通知另一个属性财产变了。因此它导致更简单的视图模型逻辑。

+2

如果你能展示一些XAML,我会赞成这个。不鼓励“仅链接”答案。 –

+0

@JanDotNet请添加一些XAML。 –

+2

根据需要添加了代码示例;) – JanDotNet

相关问题