使用按钮打开WPF弹出窗口

时间:2014-07-25 20:24:55

标签: c# wpf popup icommand relaycommand

我试图用按钮打开Popup并实现了一个基本的ICommand。该按钮绑定到ICommand OpenPopupCommand,而Popup IsOpen属性绑定到" IsOpen" OnPropertyChanged。我的思考过程是将Popup.IsOpen属性绑定到ICommand以及让IT触发OnPropertyChange但是无法使其工作。我想我已经接近但无法弄清楚。这是我到目前为止的代码:

    #region ICommand Members

    private ICommand _openPopupCommand;
    public ICommand OpenPopupCommand
    {
        get
        {
            if (_openPopupCommand == null)
                _openPopupCommand = new RelayCommand(param => OpenPopupExecute(param));
            return _openPopupCommand;
        }
        set 
        {
            _openPopupCommand = value;
        }
    }

    #endregion

    #region Methods

    public void OpenPopupExecute(object parameter)
    {
        parameter = true;
        OnPropertyChanged("IsOpen");
    }

    #endregion

按钮"弹出" Popup和Popup XAML:

<Popup x:Name="FieldsPopup" Placement="Center" Width="400" Height="250" IsOpen="{Binding IsOpen}">
                    <StackPanel>
                        <TextBlock Background="LightBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="250" Width="350" TextAlignment="Center" >This is a popup</TextBlock>
                    </StackPanel>
                </Popup>
<Button Name="button_PatientIdentifierList" Width="23" Height="23" Grid.Column="2" Foreground="Black" Background="#FFCDCDCD" BorderBrush="#FF707070" Margin="3.4,4,4,0" VerticalAlignment="Top" Command="{Binding OpenPopupCommand}"/>

1 个答案:

答案 0 :(得分:3)

您提出了PropertyChange通知,但我没有看到您实际在任何地方更改了该属性。

除非我弄错了,否则此处的代码会使用CommandParameter(此处称为parameter)并将其设置为true

public void OpenPopupExecute(object parameter)
{
    parameter = true;
    OnPropertyChanged("IsOpen");
}

但是在你的XAML中,Button.CommandParameter并没有绑定到任何东西

<Button Command="{Binding OpenPopupCommand}"/>

所以我怀疑parameter只是null,并且实际上并没有在这里做任何事情。

您似乎缺少的是实际的IsOpen属性定义,并在命令的执行代码中将其设置为true:

private bool _isOpen;
public bool IsOpen
{
    get
    {
        return _isOpen;
    }
    set 
    {
        _isOpen = value;
        OnPropertyChanged("IsOpen");
    }
}

public void OpenPopupExecute(object parameter)
{
    IsOpen = true; // Will call OnPropertyChanged in setter
}

作为旁注,我真的不喜欢WPF的默认PopupControl,并且如果你决定讨厌WPF的默认{{}},我会有custom UserControl version of it on my blog {{} 1}}:}