我正在努力掌握已编译的数据绑定概念。我有一个视图 (MainPage),其中包含一个 ListBox 和一个用于该 ListBox 的数据模板 (ItemTemplate)。MainPage 有一个 MainPageViewModel,其中包含一个 ObservableCollection 的 ItemViewModel。ItemViewModel 仅包含一个属性名称。
主页:
<Page x:Class="TestApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestApp">
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ItemDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListBox ItemsSource="{x:Bind ViewModel.Items}"
ItemTemplate="{StaticResource ItemTemplate}" />
</Grid>
</Page>
Run Code Online (Sandbox Code Playgroud)
包含数据模板的资源字典:
<ResourceDictionary
x:Class="TestApp.ItemDictionary"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestApp">
<DataTemplate x:Key="ItemTemplate" x:DataType="local:ItemViewModel">
<TextBlock Text="{x:Bind Name}" />
</DataTemplate>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
这段代码可以编译,但是当我运行它时,与 Name 属性的绑定失败,尽管生成了项目。如果我使用经典绑定,一切正常,如果我将数据模板直接放在 MainPage 的资源中,它也可以正常工作。我错过了什么?
最简单的应用程序:
<Page
x:Class="TestApp.MainPage"
...>
<Grid>
<TextBox />
</Grid>
</Page>
Run Code Online (Sandbox Code Playgroud)
问题:有没有什么优雅的方法可以防止在应用程序启动时在 TextBox 中设置光标(焦点)?
扩展:我真正的问题是当 TextBox 获得焦点时我有一个 PopUp 被打开。如果我点击 PopUp 中的一个元素,它应该关闭,但由于 TextBox 是我页面中的第一个可聚焦元素,它会自动获得焦点,因此 PopUp 会立即再次打开。我认为问题的核心就是上面的例子。