单击按钮时不显示wpf弹出窗口

时间:2017-06-10 09:11:46

标签: wpf

我的xaml中有一个按钮和一个弹出控件,如下所示:

using xyz
{ 
    private bool _PlanPopup = false;
    public bool PlanPopup
    {
        get { return _PlanPopup; }
        set
        {
            _PlanPopup = value;
        }
    }
    public MyView()
    {
        InitializeComponent();
        Popup4Plan.DataContext = this;
    }
    private void cmdPlanList_Click(object sender, RoutedEventArgs e)
    {
        this.PlanPopup = this.PlanPopup ? false : true;
    }
}

我从我的代码隐藏中设置此Popup的DataContext,如下所示: -

我的观点背后的代码: -

{{1}}

2 个答案:

答案 0 :(得分:1)

如果要将View绑定到自身的属性,请将该属性设为依赖属性。

public bool IsOpen
{
    get
    {
        return (bool)GetValue(IsOpenProperty);
    }
    set
    {
        SetValue(IsOpenProperty, value);
    }
}

public static readonly DependencyProperty IsOpenProperty =
    DependencyProperty.Register("IsOpen", typeof(bool), typeof(MyView), new PropertyMetadata(false));

要快速键入propdp [tab] [tab]并填写空白。

此外:

this.PlanPopup = this.PlanPopup ? false : true;

这样看起来好多了:

this.PlanPopup = !this.PlanPopup;

答案 1 :(得分:0)

要使绑定属性更新起作用,您需要实现INotifyPropertyChanged。例如,如下所示。

public class XYZ : INotifyPropertyChanged
{

    private bool isOpen;

    public bool IsOpen {
        get { return this.isOpen; }
        set {
            this.isOpen = value;
            this.OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

使用此代码,XYZ的实例将通知属性IsOpen已更改,并且任何绑定的视图元素将重新获取IsOpen的值。