WPF에서 RoutedCommands를 고민하려고합니다. 나는 그들이 서로 다른 UI 요소와 모델 사이의 결합을 줄이는 방법을 좋아하지만 윈도우에 자식 인 사용자 지정 컨트롤에 대해 바인딩을 작동시키는 것처럼 보이지 않습니다. 나는 이것이 WPF 마법사 중 하나에 대한 몇 가지 쉬운 creds 될 것 같아요!하위 요소로 묶인 RoutedCommands가 실행되지 않습니다.
라우팅 된 명령 :
using System.Windows.Input;
namespace Wpf.RoutedCommands
{
public static class Commands
{
public static readonly RoutedCommand SayHi = new RoutedCommand();
}
}
메인 창 XAML :
<Window x:Class="Wpf.RoutedCommands.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Wpf.RoutedCommands"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!-- uncommenting the below makes it work but introduces coupling -->
<!--<Window.CommandBindings>
<CommandBinding Command="{x:Static local:Commands.SayHi}" Executed="cmdSayHi" CanExecute="cmdCanSayHi"></CommandBinding>
</Window.CommandBindings>-->
<DockPanel LastChildFill="True">
<Button DockPanel.Dock="Bottom" Content="Say Hi!" Command="{x:Static local:Commands.SayHi}" />
<local:Greeter x:Name="Greeter" />
</DockPanel>
메인 창 코드 :-)
여기 밖으로 시도 할 수있는 몇 가지 예제 코드는 :
using System.Windows.Input;
namespace Wpf.RoutedCommands
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
// these two will be used if you uncomment the command bindings in XAML
private void cmdCanSayHi(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
private void cmdSayHi(object sender, ExecutedRoutedEventArgs e) => Greeter.SayHi();
}
}
사용자 지정 컨트롤 ("손님 맞이 도우미") XAML :
<UserControl x:Class="Wpf.RoutedCommands.Greeter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Wpf.RoutedCommands"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static local:Commands.SayHi}" Executed="cmdSayHi" CanExecute="cmdCanSayHi"/>
</UserControl.CommandBindings>
<Grid>
<Label x:Name="Label" />
</Grid>
손님 맞이 도우미 코드 : 당신이 WPF 프로젝트를 만들고 사용하는 경우
using System.Windows.Input;
namespace Wpf.RoutedCommands
{
public partial class Greeter
{
public Greeter()
{
InitializeComponent();
}
private void cmdSayHi(object sender, ExecutedRoutedEventArgs e) => SayHi();
private void cmdCanSayHi(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
public void SayHi() => Label.Content = "Hi!";
}
}
하면 위의 버튼 것을 볼 수 있습니다 주 창에서 사용할 수 없습니다. 디버깅을하면 Greeter.cmdCanSayHi
메서드가 호출되지 않는다는 것을 알 수 있습니다.
주 창에서 휴면 XAML을 주석 처리하지 않으면 모든 것이 작동합니다. 그래서 : 왜 창에서 명령을 바인딩 할 수 있지만 자식 컨트롤에서 바인딩 할 수 있습니까? 타이밍을 렌더링하는 것과 관련이 있습니까?
글쎄, 확실히 설명해. 라우트 된 명령이 그렇게 설계된 이유도 알고 있습니까? –