回答者様、すみません。回答と齟齬が発生しますが、わかりにくいので質問を修正します
①WPFでファイル監視アプリを作り、ファイルが新規作成された時点でWindowのTitleを弄ろうとしたところ、FileSystemWatherの部分でエラー発生しました。
System.InvalidOperationException: このオブジェクトは別のスレッドに所有されているため、呼び出しスレッドはこのオブジェクトにアクセスできません。
②FileSystemWatherがUIと別スレッドなので
SynchronizingObject=this;として解決できると思いましたが、次のエラーが出ます。
型 'Window1' を 'System.ComponentModel.ISynchronizeInvoke' に暗黙的に変換できません。明示的な変換が存在します。(cast が不足していないかどうかを確認してください)
といわれたので型変換しましたが、エラーが出ます。
どのサイトを見てもみなさんキャストしてないのでどうすればいいかわかりません。
同じような質問
WPF - WPFでUserControlを使った場合にMainWindowにあるMethodにFileSystemWatherでアクセスしたい(56813)|teratail
当該コード
C#
1 2 /// <summary> 3 /// Interaction logic for Window1.xaml 4 /// </summary> 5 public partial class Window1 : Window 6 { 7 public Window1() 8 { 9 InitializeComponent(); 10 } 11 12 void window1_Loaded(object sender, RoutedEventArgs e) 13 { 14 try 15 { 16 //Create watch object 17 FileSystemWatcher filewacher = new FileSystemWatcher(TargetFolderPath); 18 19 //UIthred 20// filewacher.SynchronizingObject = this; ←②キャストミスといわれる。GetWindowとかでキャストしてもダメ 21 22 //Reg EventHandler 23 filewacher.Created += Function; 24 25 //Start wacher 26 filewacher.EnableRaisingEvents = true; 27 } 28 catch(Exception objException) 29 { 30 Console.WriteLine(objException.Message); 31 } 32 } 33 34 35 /// <summary> 36 /// when new create file ,this method run this event 37 /// </summary> 38 /// <param name="sender">Event</param> 39 /// <param name="objEventArguments">argument</param> 40 void Function(object sender,FileSystemEventArgs objEventArguments) 41 { 42 try 43 { 44 //the created file path 45 string FilePath = objEventArguments.FullPath; 46 //WindowのTitleを変更するよ 47 window1.Title = FilePath + "というファイル検知したよ"; 48 } 49 catch(Exception objException) 50 { 51 Console.WriteLine(objException.Message); //←①ここで例外をキャッチされた 52 } 53 } 54 } 55

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/16 04:25 編集
2018/06/16 04:08 編集
2018/06/16 04:33