実現したいこと
- マウスに追従して図形が動くWPFアプリケーションを作りたい
- 上の目的が達成できて,WPFアプリケーションであれば,使うツールは何でもいい
- WPF初心者です
困っていること
WPFで図形をマウスに追従させるのコードビハインドを汚す場合をほぼ丸写ししたのですが,マウスをウィンドウ上で動かすと,VM.X.Value = mousepos.X;
の行で以下のようなエラーメッセージが出てきます.
System.NullReferenceException: 'Object reference not set to an instance of an object.' projectorButtonWpf.MainWindow.VM.get が null を返しました。
コード
xaml
1<Window x:Name="Window" x:Class="projectorButtonWpf.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:projectorButtonWpf" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="600" Width="600" MouseMove="Window_MouseMove"> 9 10 <Grid> 11 <Canvas MouseMove="MouseMoveHandler" 12 Background="#00FFFACD"> 13 <Rectangle Stroke="Green" 14 StrokeThickness="5" 15 Width="50" 16 Height="50" 17 HorizontalAlignment="Left" 18 VerticalAlignment="Top"> 19 <Rectangle.RenderTransform> 20 <TransformGroup> 21 <TranslateTransform 22 X="{Binding X.Value}" 23 Y="{Binding Y.Value}"/> 24 </TransformGroup> 25 </Rectangle.RenderTransform> 26 </Rectangle> 27 </Canvas> 28 </Grid> 29</Window>
cs
1using System.Windows.Input; 2using Reactive.Bindings; 3using System.Diagnostics; 4 5namespace projectorButtonWpf 6{ 7 public partial class MainWindow : System.Windows.Window 8 { 9 public class MainWindowViewModel 10 { 11 public ReactivePropertySlim<double> X { get; } = new ReactivePropertySlim<double>(); 12 public ReactivePropertySlim<double> Y { get; } = new ReactivePropertySlim<double>(); 13 } 14 15 public MainWindow() 16 { 17 InitializeComponent(); 18 } 19 private MainWindowViewModel VM => (MainWindowViewModel)DataContext; 20 21 private void Window_MouseMove(object sender, MouseEventArgs e) 22 { 23 var mousepos = e.GetPosition(this); 24 VM.X.Value = mousepos.X; //この行でエラーが出る 25 VM.Y.Value = mousepos.Y; 26 } 27 } 28} 29

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/01/10 10:15