【问题标题】:How to bind Button on a UserControl to a Command in the Parent Control?如何将用户控件上的按钮绑定到父控件中的命令?
【发布时间】:2019-09-12 11:59:03
【问题描述】:

我在将UserControl 中的Button 绑定到父级中的Command 时遇到问题。

我有一个显示搜索结果数据的UserControl (SearchView)。 其中包含一个Menu,我想在其中包含一个重置用户设置(字体大小、排序等)的功能。由于有多个这样的我想在其父控件(MainView)中具有重置功能。

MainViewXaml:

<UserControl x:class="UI.MainView"
xmlns:ui="clr-namespace:Project.Main.UI">
//some stuff here
<ui:SearchView/>
//some stuff here
</UserControl>

MainView.xaml.vb:

Namespace UI

Public Class MainView

Public ReadOnly Property ResetCommand As New DelegateCommand(AddressOf ResetEinstellungen)

Public Sub ResetEinstellungen()
      //Reset Einstellungen ...
End Sub

搜索视图:

<UserControl x:Class="UI.SearchView"
xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm">
<Grid>
//Table Stuff
</Grid>
<Menu>
    <MenueItem Header="Reset"
               x:Name="ResetButton">
          <dxmvvm:Interaction.Behaviors>
                    <dxmvvm:EventToCommand EventName="Click"
                                           Command="{Binding ResetCommand , RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl} }">
                    </dxmvvm:EventToCommand>
          </dxmvvm:Interaction.Behaviors>
     </MenuItem>
</Menu>

我已经尝试了一些变化。 我要避免的是通过 ElementName 引用 MainView,因为我想在其他视图中使用 UserControl。

【问题讨论】:

    标签: wpf vb.net xaml binding


    【解决方案1】:

    我做了一个实验。

    这对我有用:

       <MenuItem Header="Reset"
                  Command="{Binding DataContext.ResetCommand , RelativeSource={RelativeSource AncestorType=UserControl} }"/>
    

    注意:

    DataContext.CommandName

    你可以在 menuitem 上使用 command 而不是 eventtocommand。

    【讨论】:

    • 所以我或多或少已经对了,但是当我点击它时我仍然无法让它执行我的方法,这对我来说很奇怪。 MainView 位于 DialogWindow 中,它是 ContainerControlledLifetimeManager 的一部分,但几乎没有准系统,所以我现在真的只是在猜测我的问题是什么。我也没有从调试器那里得到任何信息,为什么它没有绑定或为什么没有执行。
    【解决方案2】:

    尝试将AncestorLevel 设置为2,因为1 的默认值将绑定到SearchView 而不是MainView:

    Command="{Binding ResetCommand , RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=2, AncestorType=UserControl} }
    

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 2010-12-27
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多