【问题标题】:using routed events within Silverlight user controls在 Silverlight 用户控件中使用路由事件
【发布时间】:2011-08-09 20:49:00
【问题描述】:

在我当前的项目文件中,我有一个用户控件,该控件应用了情节提要动画。当在页面中单击按钮时,情节提要开始并基本上将控件直观地呈现给用户。故事板作为资源驻留在当前页面中

<navigation:Page.Resources>
    <Storyboard x:Name="PreferncesOpen">....</Storyboard x:Name="PreferncesOpen">
        </navigation:Page.Resources>

在页面内我有一个按钮,我有一个点击事件来启动故事板

private void btnOpenPreferences_Click(object sender, RoutedEventArgs e)
    {
        preferencesPanel.Visibility = System.Windows.Visibility.Visible;
        PreferncesOpen.Begin();
    }

在 userControl (preferencesPanel) 中,我有一个按钮,单击该按钮需要关闭/折叠用户控件。我计划使用 Visibility.collapsed 来完成这项工作。我假设我需要使用路由命令,因为按钮位于用户控件中,但需要在包含控件的页面中调用操作?我对路由命令还是新手,我认为这是正确的方法。我只是不确定如何单击用户控件中的按钮并让它修改或执行将影响页面(此控件所在的页面)如何更改或该部分影响页面中其他元素的命令?例如,当在用户控件中单击按钮时,我希望将用户控件的可见性设置为折叠。我还希望重新调整主页内网格列之一的宽度。我过去曾使用页面背后的代码完成此操作,但我试图将其中的一些分开,我认为路由命令将是要走的路吗? 如果有任何提示,我将不胜感激。

提前谢谢你

【问题讨论】:

    标签: wpf silverlight mvvm user-controls routed-commands


    【解决方案1】:

    标题有点误导,如果我理解正确,您是在询问命令而不是路由事件。

    这是使用 Prism 库中的 DelegateCommand&lt;T&gt; 的示例;这恰好是我个人的喜好。

    标记:

    <Button x:Name="MyButton" Content="Btn" Command="{Binding DoSomethingCommand}"/>
    

    代码隐藏* 或 ViewModel :

    (* 如果您不使用 MVVM,请确保添加 MyButton.DataContext = this;,以便您确定按钮可以有效地数据绑定到您的代码)

    public DelegateCommand<object> DoSomethingCommand
    {
        get 
        { 
            if(mDoSomethingCommand == null)
                mDoSomethingCommand = new DelegateCommand(DoSomething, canDoSomething);
            return mDoSomethingCommand;
        }
    
    private DelegateCommand<object> mDoSomethingCommand;
    
    // here's where the command is actually executed
    void DoSomething(object o)
    {}
    
    // here's where the check is made whether the command can actually be executed
    // insert your own condition here
    bool canDoSomething(object o)
    { return true; }
    
    
    // here's how you can force the command to check whether it can be executed
    // typically a reaction for a PropertyChanged event or whatever you like
    DoSomethingCommand.RaiseCanExecuteChanged();
    

    传递给上述函数的参数是 CommandParameter 依赖属性(在 Prism 中,它是一个附加属性以及 Command 属性,如果我没记错的话)。 设置后,您可以将您选择的值传递给您希望执行的命令。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 2013-02-11
      • 1970-01-01
      • 2011-06-11
      • 2012-04-26
      • 1970-01-01
      相关资源
      最近更新 更多