Last active
January 10, 2023 06:03
-
-
Save runceel/5e6d7e62ccc487f52044f06cd71f6559 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Window | |
x:Class="WpfApp3.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:local="clr-namespace:WpfApp3" | |
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | |
Title="MainWindow" | |
Width="800" | |
Height="450" | |
mc:Ignorable="d"> | |
<StackPanel x:Name="stackPanel"> | |
<Button Click="AddTextBlock_Click" Content="Add a TextBlock." /> | |
</StackPanel> | |
</Window> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Xaml.Behaviors; | |
using Reactive.Bindings; | |
using Reactive.Bindings.Interactivity; | |
using System; | |
using System.ComponentModel; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Data; | |
namespace WpfApp3; | |
/// <summary> | |
/// Interaction logic for MainWindow.xaml | |
/// </summary> | |
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
DataContext = new VM(); | |
} | |
// XAML で書く方法に近づけるならこんな雰囲気になりますが… | |
private void AddTextBlock_Click(object sender, RoutedEventArgs e) | |
{ | |
var textBlock = new TextBlock | |
{ | |
Text = DateTime.Now.ToString(), | |
}; | |
var eventToReactiveCommand = new EventToReactiveCommand(); | |
Interaction.GetTriggers(textBlock).Add( | |
new Microsoft.Xaml.Behaviors.EventTrigger(nameof(MouseDown)) | |
{ | |
Actions = | |
{ | |
new EventToReactiveCommand | |
{ | |
Command = ((VM)DataContext).AlertCommand, | |
}, | |
}, | |
}); | |
stackPanel.Children.Add(textBlock); | |
} | |
// でも、特に拘りがないならイベントを普通にイベントを購読して、そこから呼ぶのでいいと思います | |
private void AddTextBlock_Click2(object sender, RoutedEventArgs e) | |
{ | |
var textBlock = new TextBlock | |
{ | |
Text = DateTime.Now.ToString(), | |
}; | |
textBlock.MouseDown += (_, _) => ((VM)DataContext).AlertCommand.Execute(); | |
stackPanel.Children.Add(textBlock); | |
} | |
} | |
class VM : INotifyPropertyChanged | |
{ | |
public event PropertyChangedEventHandler? PropertyChanged; | |
public ReactiveCommand AlertCommand { get; } | |
public VM() | |
{ | |
AlertCommand = new ReactiveCommand() | |
.WithSubscribe(() => MessageBox.Show("押された")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment