我想創建一個可以搜索檔案并跟蹤以前使用的檔案的文本框。所以我做了一個用戶控制元件,DependecyProperty
它應該給我文本框的當前文本和一個按鈕。但是每次我嘗試系結到 DependencyProperty 時,系結到它的屬性仍然是空的。簡而言之,控制元件如下所示:
<UserControl
<!-- ... -->
x:Name="PTB">
<AutoSuggestBox x:Name="SearchBox"
Text="{Binding ElementName=PTB, Path=FilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding PickFileCommand}" />
</UserControl
我有這個簡單的 ViewModel 用于用戶控制元件
public string FilePath
{
get => _filePath;
set => SetProperty(ref _filePath, value);
}
public async Task PickFile()
{
// ...
}
以及用于用戶控制元件的此代碼隱藏
public readonly static DependencyProperty FilePathProperty =
DependencyProperty.Register("FilePath", typeof(string), typeof(PathTextBox), new PropertyMetadata("", new PropertyChangedCallback(OnTextChanged)));
public string FilePath
{
get => (string)GetValue(FilePathProperty);
set => SetValue(FilePathProperty, value);
}
private static void OnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
if (dependencyObject is PathTextBox ptb && e.NewValue is string s)
{
ptb.SearchBox.Text = s;
ptb.FilePath = s;
}
}
當我嘗試在我的MainPage.xaml
:
<customcontrols:PathTextBox x:Name="SearchBox"
KeyUp="SearchBox_KeyUp"
FilePath="{Binding ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
和MainPage.xaml.cs
private async void SearchBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
await ViewModel.OpenSqlFile(ViewModel.ScriptFilePath);
}
}
然后ViewModel.ScriptFilePath
仍然是空的,即使我確實系結了它。我用 x:Bind 等嘗試了一些不同的東西,但我找不到在 MVVM 中干凈地實作它的方法。如果有幫助,我正在使用 CommunityToolkit.Mvvm 庫。有任何想法嗎?
uj5u.com熱心網友回復:
從您的代碼中,我假設您擁有ViewModel
in MainPage.xaml.cs。然后您需要將ViewModel添加到您的系結代碼中。
<customcontrols:PathTextBox
x:Name="SearchBox"
KeyUp="SearchBox_KeyUp"
FilePath="{Binding ViewModel.ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
甚至更好,使用x:Bind ViewModel.ScriptFilePath
.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/506345.html
上一篇:.NetMAUI-如何系結到作為KeyValuePair串列的物件中的屬性
下一篇:使用模板懸停時如何使按鈕突出顯示