我有一個 WPF 應用程式Framework = .NET 6.0,我正在使用CommunityToolkit.MvvmMVVM 實作。我需要創建一個文本框,用戶可以在其中拖放檔案夾,并且ViewModel我需要獲取此路徑。我嘗試MVVM在我xaml.cs的 .
我的文本框 XAML:
<TextBox Grid.Row="0" Grid.Column="1"
Name="TxtPath"
AllowDrop="True"
Drop="TxtPath_Drop"
PreviewDragOver="TxtPath_PreviewDragOver"
Text="{Binding PathText}">
</TextBox>
xaml.cs 后面的代碼:
private void TxtPath_Drop(object sender, DragEventArgs e)
{
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
{
TxtPath.Text = files[0];
}
}
private void TxtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
我的視圖模型:
[ObservableProperty]
private string? pathText;
我希望這會PathText在拖放操作更改文本時更新我的??內容,但事實并非如此。我得到了一個null值PathText。我已經確認它files[0]具有有效的路徑值,并且我也可以在文本框中直觀地看到放置的檔案夾路徑。
奇怪的是,我的代碼后面有第二種方法,用戶可以單擊 [ Browse ] 按鈕,然后也選擇檔案夾,為此我使用下面的方法,完成后PathText,我的 ViewModel 中的更新為預期的。
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
{
var folderBrowserDialog = new FolderBrowserDialog();
if (Directory.Exists(TxtPath.Text))
{
folderBrowserDialog.Reset();
folderBrowserDialog.SelectedPath = TxtPath.Text;
}
if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TxtPath.Text = folderBrowserDialog.SelectedPath;
}
}
我在這里想念什么?為什么button_Click事件更新系結而不更新textbox_Drop事件?
編輯:錯字
uj5u.com熱心網友回復:
的 UpdateSourceTrigger的默認值為TextBox.TextLostFocus,因此當 TextBox 失去焦點時,系結源將被更新。請參閱如何:控制 TextBox 文本何時更新 Source。
解決方案是設定 UpdateSourceTrigger PropertyChanged。
Text="{Binding PathText, UpdateSourceTrigger=PropertyChanged}"
我不確定在第二種情況下會發生什么,但我猜這個序列會以某種方式改變你的應用程式中的焦點并觸發更新。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527028.html
標籤:C#wpf虚拟机拖放
下一篇:從另一個視窗獲取資料
