Skip to content

Instantly share code, notes, and snippets.

@runceel
Last active January 10, 2023 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runceel/5e6d7e62ccc487f52044f06cd71f6559 to your computer and use it in GitHub Desktop.
Save runceel/5e6d7e62ccc487f52044f06cd71f6559 to your computer and use it in GitHub Desktop.
<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>
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