【问题标题】:WPF MVVM hiding button using BooleanToVisibilityConverter使用 BooleanToVisibilityConverter 的 WPF MVVM 隐藏按钮
【发布时间】:2014-01-01 10:29:23
【问题描述】:

在我的 WPF 应用程序中,我试图根据用户选择的选项更改按钮的可见性。在加载时,我希望其中一个按钮不可见。我正在使用内置值转换器 BooleanToVisibilityConverter。但是它不起作用,因为按钮在加载时出现。我已将属性更改为真假,没有区别。下面是我的代码,我看不到我缺少什么?

我的视图模型中的属性

 bool ButtCancel
    {
        get { return _buttCancel; }
        set
        {
            _buttCancel = value;
            OnPropertyChanged("ButtCancel");
        }
    }

在我的 app.xaml 中

 <Application.Resources>       
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>

在我的 MainWindow.xaml 中

 <Button Grid.Column="2" 
      Command="{Binding CommandButtProgressCancel}" 
      Content="Cancel" 
      Visibility="{Binding ButtCancel, Converter={StaticResource BoolToVis}}"
      IsEnabled="{Binding ButtCancelEnabled}" 
      Height="50" Width="120" 
      HorizontalAlignment="Center" 
      VerticalAlignment="Center" Margin="0,0,50,20"/>

【问题讨论】:

  • 您的ButtCancel 属性是public 吗?它在您的代码摘录中没有访问修饰符,这将使它成为private,因此对绑定引擎不可见。此外,您不应该绑定 IsEnabled 属性;让按钮使用命令的CanExecute 回调来确定自己的状态。
  • @MikeStrobel,当然默认访问修饰符是internal 而不是private
  • 是的,不敢相信我错过了!它不公开
  • @Sheridan 对于顶级声明,默认为internal;对于类成员,包括嵌套类型声明,它是private

标签: c# wpf xaml mvvm


【解决方案1】:

对于初学者来说,如果您使用的是Command,那么您不需要绑定IsEnabled,命令实现应该决定这一点。

其次,ViewModel 到 View 的绑定往往会在稍后的阶段发生,所以最好也为绑定设置一个默认值,像这样

Visibility="{Binding ButtCancel, Converter={StaticResource BoolToVis}, FallbackValue=Hidden}"

第三,正如 Mike 指出的,确保您的属性是公开的,因为 ViewModel 和 View 是两个独立的类。

【讨论】:

  • internal 属性也不起作用。绑定引擎不知道绑定的声明位置,因此所有非公共成员都被同等对待(实际上是private)。
  • 哦,我不知道,谢谢 Mike,我会调整我的答案。
【解决方案2】:

您可以使用DataTrigger,而不是使用转换器。

<Button Grid.Column="2" Command="{Binding CommandButtProgressCancel}" Content="Cancel" 
        Visibility="{Binding ButtCancel, Converter={StaticResource BoolToVis}}" 
        IsEnabled="{Binding ButtCancelEnabled}" Height="50" Width="120"
        HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,50,20">
    <Button.Style>
        <Style TargetType={X:Type Button}>
            <!-- This would be the default visibility -->
            <Setter Property="Visibility" Value="Visible" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ButtCancel, UpdateSourceTrigger=PropertyChanged}" Value="True">
                    <Setter Property="Visibility" Value="Hidden" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

将 ViewModel 的属性更新为 public

public bool ButtCancel
{
    get { return _buttCancel; }
    set
    {
        _buttCancel = value;
        OnPropertyChanged("ButtCancel");
    }
}

并确保您的 MainWindow 的 DataContext 设置为 ViewModel

【讨论】:

  • 如果您尝试使用 MVVM 模式(正如 OP 所说),触发器并不是最好的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多