Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c# - WPF MVVM hiding button using BooleanToVisibilityConverter

In my WPF application I am trying to change the visibility of a button depending on the options chosen by a user. On load I want one of the buttons to not be visible. I am using the in built value converter BooleanToVisibilityConverter. However it's not working as the button is appearing at load time. I have changed the property to both true and false, makes no difference. Below is my code, I can't see what I'm missing?

The property in my View Model

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

In my app.xaml

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

In my 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"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For starters mate, if you're using a Command, then you don't need to bind IsEnabled, the command implementation should decide this.

Secondly, the binding of a ViewModel to a View tends to happen at a bit of a later stage, so it's best to also set a default value for the binding, like so

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

Third, as Mike pointed out, ensure that your property is public, since the ViewModel and the View are two separate classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...