WPF

[WPF]コンボボックスのリストを変更した時にselectedItemを見失うのを防ぐ

Mohmongar
コンボボックスのリストの中身を変更(ソートとか)した時にselectedItemを見失うのを防ぐ。Tagプロパティを一時保存に使用するのであまり美しくない? private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var combo = (ComboBox)sender; object item = combo.SelectedItem; if (item == null) { combo.SelectedItem = combo.Tag; } else { combo.Tag = combo.SelectedItem; } }

[WPF]DataGridをクリックしたセルの位置を調べる

Mohmongar
C# WPF環境でDataGridをクリックした時のセル位置を求める。VisualTreeHelperを使ってDataGridCellとDataGridRowをたぐってcolumnとrowを調べる。formと違ってめんどくさい。他にも方法があるかもしんない。 // // DataGrid dg ... Clicked Control // Point pos ... Position in DataGrid axis // HitTestResult result = VisualTreeHelper.HitTest(dg, pos); if (result == null) { return; } DependencyObject dep = result.VisualHit; while (!(dep is DataGridCell || dep is DataGridRow)) { if (dep == null) { return null; } dep = VisualTreeHelper.GetParent(dep); } DataGridCell dgcell = null; int c = -1; if (dep is DataGridCell) { dgcell = dep as DataGridCell; c = dgcell.

[WPF]Drawing.BitmapをBitmapSourceへ変換

Mohmongar
昔のDLLがBitmapしか対応してないので、System.DrawingのBitmapをWPFのBitmapSourceへ変換する。 [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); public BitmapSource BmpToWPFBmp(System.Drawing.Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); BitmapSource source; source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(hBitmap); return source; }

[WPF]Dispatcherで別スレッドからUIアクセス

Mohmongar
WPFでUIスレッドとは別のスレッドからUIを変更するときの作法。いつもやりかた忘れるのでメモ。formの場合のInvokeRequiredとinvokeに当たる。状況に応じてInvokeをBeginInvokeで非同期にするのもあり。VSでCheckAccessが入力補完対象にならないのはなぜだろう。 if (mycontrol.Dispatcher.CheckAccess()) { mycontrol.Content = "test"; } else { mycontrol.Dispatcher.Invoke((Action)(() => { mycontrol.Content = "test"; })); }

[WPF]コントロールの座標を調べる

Mohmongar
C# WPF環境で親コントロール座標系からの子コントロールのXY座標を求める。これだけのことなのに結構トリッキーな処理が必要。子cの座標系の(0,0)を親pの座標系に変換する、あれ?普通か・・というかWPFではコントロールの左上座標をしめすプロパティLeftとかTopととがないんだよな。 // // p ... parent control // c ... child control // Point d = c.TranslatePoint(new Point(0, 0), p); //