我想要创建一个文本框,它可以搜索文件,也可以跟踪以前使用过的文件。因此,我使用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库,如果这有帮助的话。有什么想法吗?
发布于 2022-08-24 12:27:59
从您的代码中,我假设您在MainPage.xaml.cs.中有ViewModel
然后,您需要向绑定代码中添加ViewModel。
<customcontrols:PathTextBox
x:Name="SearchBox"
KeyUp="SearchBox_KeyUp"
FilePath="{Binding ViewModel.ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
或者更好的是使用x:Bind ViewModel.ScriptFilePath
。
https://stackoverflow.com/questions/73472509
复制相似问题