如何将UserControl上的Button绑定到父控件中的命令?

问题描述 投票:1回答:2

我有一个问题,即将Button中的UserControl绑定到父母的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
2个回答
0
投票

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

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

1
投票

我把一个实验放在一起。

这对我有用:

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

注意:

DataContext.CommandName

您可以在menuitem而不是eventtocommand上使用命令。

© www.soinside.com 2019 - 2024. All rights reserved.