如何回调到自定义控件WPF中的代码隐藏



我正在使用wpf。我创建了一个自定义控件。在这个控件中,我有多个按钮。我可以将按钮命令绑定到视图模型。然而,在这个应用程序中,我需要回调回代码返回文件,而不是viewmdoel。我该怎么做?

以下是我的自定义控件示例:

<Grid>
<StackPanel Orientation="Horizontal" Grid.Row="3">
<Button Content="Button A" Command="{Binding SwitchToABCCommand}">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding CurRegion}" Value="ABC">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<Button Content="Button B" Command="{Binding SwitchToEFGCommand}">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding CurRegion}" Value="DEF">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
</Grid>

然后我有另一个使用这个自定义控件的窗口。

主窗口视图Model.cs

public ICommand SwitchToABCCommand { get; }
public ICommand SwitchToDEFCommand { get; }
public MainWindowViewModel()
{
SwitchToABCCommand = new DelegateCommand(HandleSwitchToABCCommand);
SwitchToEFGCommand = new DelegateCommand(HandleSwitchToEFGCommand);
}
private void HandleSwitchToABCCommand()
{
}
private void HandleSwitchToDEFCommand()
{
}

我想回叫MainWindow.xaml.cs

private void SwitchToABC(object sender, RoutedEventArgs e)
{
}
private void SwitchToDEF(object sender, RoutedEventArgs e)
{
}

我试过做:

<Button Content="Button A" Click="SwitchToABC">

但这只能回调到MyCustomControl.xaml.cs。如何回叫MainWindow.xaml.cs?

谢谢

事件处理程序必须与XAML标记在同一类中定义。如果在MyCustomControl.xaml.cs中定义SwitchToABC,则可以从MainWindow调用事件处理程序:

private void SwitchToABC(object sender, RoutedEventArgs e)
{
MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
if (parentWindow != null)
{
parentWindow.SomeHandler(sender, e);
}
}

请注意,这在控件和窗口之间创建了强耦合。

绑定到控件XAML中的SwitchToABCCommand命令也会创建到视图模型的间接耦合。更好的方法是向控件添加一个命令属性,并将其绑定到视图模型命令属性,例如:

<MyCustomControl YourCommand="{Binding SwitchToABCCommand }"  />

最新更新