[英]Properly bind DependencyProperty of UserControl in MVVM
I wanted to create a textbox that can search for files and also keeps track of previously used files.我想创建一个可以搜索文件并跟踪以前使用的文件的文本框。 So I made a user control with a DependecyProperty
that should give me the current text of the textbox and a button.所以我用一个DependecyProperty
制作了一个用户控件,它应该给我文本框的当前文本和一个按钮。 But everytime I try to bind to the DependencyProperty, the property that binds to it remains empty.但是每次我尝试绑定到 DependencyProperty 时,绑定到它的属性仍然是空的。 In short, the control looks like this:简而言之,控件如下所示:
<UserControl
<!-- ... -->
x:Name="PTB">
<AutoSuggestBox x:Name="SearchBox"
Text="{Binding ElementName=PTB, Path=FilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding PickFileCommand}" />
</UserControl
I have this simple ViewModel for the user control我有这个简单的 ViewModel 用于用户控件
public string FilePath
{
get => _filePath;
set => SetProperty(ref _filePath, value);
}
public async Task PickFile()
{
// ...
}
and this code-behind for the user control以及用于用户控件的此代码隐藏
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;
}
}
And when I try to use it like this in my MainPage.xaml
:当我尝试在MainPage.xaml
中像这样使用它时:
<customcontrols:PathTextBox x:Name="SearchBox"
KeyUp="SearchBox_KeyUp"
FilePath="{Binding ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
and MainPage.xaml.cs
和MainPage.xaml.cs
private async void SearchBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
await ViewModel.OpenSqlFile(ViewModel.ScriptFilePath);
}
}
then ViewModel.ScriptFilePath
remains empty, even though I did bind to it.然后ViewModel.ScriptFilePath
保持为空,即使我确实绑定到它。 I tried a couple of different things with x:Bind etc., but I couldn't find a way to cleanly implement it in MVVM.我用 x:Bind 等尝试了一些不同的东西,但我找不到在 MVVM 中干净地实现它的方法。 I'm using the CommunityToolkit.Mvvm library, if that helps.如果有帮助,我正在使用 CommunityToolkit.Mvvm 库。 Any ideas?有任何想法吗?
From your code, I assume that you have the ViewModel
in MainPage.xaml.cs .从您的代码中,我假设您在MainPage.xaml.cs中有ViewModel
。 Then you need to add ViewModel to you binding code.然后您需要将ViewModel添加到您的绑定代码中。
<customcontrols:PathTextBox
x:Name="SearchBox"
KeyUp="SearchBox_KeyUp"
FilePath="{Binding ViewModel.ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
or even better, use x:Bind ViewModel.ScriptFilePath
.甚至更好,使用x:Bind ViewModel.ScriptFilePath
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.