首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVVM中适当绑定DependencyProperty的UserControl

MVVM中适当绑定DependencyProperty的UserControl
EN

Stack Overflow用户
提问于 2022-08-24 11:40:48
回答 1查看 41关注 0票数 0

我想要创建一个文本框,它可以搜索文件,也可以跟踪以前使用过的文件。因此,我使用DependecyProperty创建了一个用户控件,该控件应该为我提供文本框和按钮的当前文本。但是每次我试图绑定到DependencyProperty时,绑定到它的属性仍然是空的。简而言之,该控件如下所示:

代码语言:javascript
运行
复制
<UserControl
    <!-- ... -->
    x:Name="PTB">

    <AutoSuggestBox x:Name="SearchBox"
                    Text="{Binding ElementName=PTB, Path=FilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

    <Button Command="{Binding PickFileCommand}" />
</UserControl

我为用户控件提供了一个简单的ViewModel

代码语言:javascript
运行
复制
public string FilePath
{
     get => _filePath;
     set => SetProperty(ref _filePath, value);
}

public async Task PickFile()
{
     // ...
}

以及用户控件的代码隐藏。

代码语言:javascript
运行
复制
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中像这样使用它时

代码语言:javascript
运行
复制
<customcontrols:PathTextBox x:Name="SearchBox"
                            KeyUp="SearchBox_KeyUp"
                            FilePath="{Binding ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

MainPage.xaml.cs

代码语言:javascript
运行
复制
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库,如果这有帮助的话。有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-24 12:27:59

从您的代码中,我假设您在MainPage.xaml.cs.中有ViewModel然后,您需要向绑定代码中添加ViewModel

代码语言:javascript
运行
复制
<customcontrols:PathTextBox
    x:Name="SearchBox"
    KeyUp="SearchBox_KeyUp"
    FilePath="{Binding ViewModel.ScriptFilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

或者更好的是使用x:Bind ViewModel.ScriptFilePath

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73472509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档