MVVM按钮可见性

时间:2018-04-18 21:01:00

标签: c# wpf xaml mvvm

我的ViewModel构造函数中有一个设置为Hidden的按钮。当用户点击某个项目时,该按钮应该可见。我的断点和消息框显示可见性的值正在变为"可见"所以我不确定我在绑定中缺少什么。

XAML:

    <Button  
        Grid.Column="0"
        Grid.Row="2"
        HorizontalAlignment="Left" 
        Margin="105,22,0,21" 
        Style="{StaticResource MetroButton}" 
        Width="90" 
        Height="57" 
        Click="btn_Update_Click" 
        RenderTransformOrigin="0.49,0.287"
        Visibility="{Binding Btn_Update_Visibility, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
        <TextBlock Text="Update Request" TextWrapping="Wrap" TextAlignment="Center"/>
    </Button>

视图模型:

项目用户可以选择:

private DataRowView select_request;
public DataRowView Select_Request
{
    get { return select_request; }
    set
    {
        select_request = value;
        OnPropertyChanged("Select_Request");

        //Get the Check Request ID
        OnSelect_RequestChange();

        //Make Update Button Visible
        OnSelect_Row();
    }
}

在XAML中将可见性绑定到的值

private string btn_update_visiblity;
public string Btn_Update_Visibility
{
    get { return btn_update_visiblity; }
    set
    {
        btn_update_visiblity = value;
        OnPropertyChanged("Btn_Update_Visibility");
    }
}

当用户选择行

时调用的方法
public void OnSelect_Row()
{
    btn_update_visiblity = "Visible";
    MessageBox.Show("Update Button is " + Btn_Update_Visibility.ToString());
}

编辑:添加构造函数 我的构造函数:

    public LandingPageMVVM()
    {
        Search_User = MyCommonValues.UserName;

        btn_update_visiblity = "Hidden";
        //Check if Manager
        #region Manager Check

        bool? manager_check = MyCommonValues.manager_check;
        if (manager_check == true)
        {
            MessageBox.Show("Welcome Manager");
            btn_review_visibility = "Visible";
        }
        else
        {
            MessageBox.Show("Welcome User");
            btn_review_visibility = "Hidden";
        }
     }

1 个答案:

答案 0 :(得分:5)

您直接设置btn_update_visibility字段的值,而不是Btn_Update_Visibility属性。这意味着永远不会调用OnPropertyChanged("Btn_Update_Visibility")方法来指示视图需要更改。

相反,您的代码应为:

public void OnSelect_Row()
{
    Btn_Update_Visibility = "Visible";
    MessageBox.Show("Update Button is " + Btn_Update_Visibility.ToString());
}

部分相关的是您对变量和方法的命名。常见的C#约定会稍微澄清你的代码会让它更像这样(还有其他一些样式改进):

private string _buttonUpdateVisibility;

public string ButtonUpdateVisibility
{
    get => _buttonUpdateVisibility;
    set
    {
        _buttonUpdateVisibility= value;
        OnPropertyChanged(nameof(ButtonUpdateVisibility));
    }
}