Sup*_*JMN 0 c# xaml win-universal-app uwp
我正在尝试通过一个简单的用例在UWP中使用已编译的绑定。
为了使XAML的可读性易于管理,我将DataTemplate的XAML提取到UserControl中。所以我改变了这个
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{x:Bind ViewModel.Items}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:ProjectItem">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind Name, Mode=OneWay}" />
<TextBlock Text="{x:Bind Description, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Page>
Run Code Online (Sandbox Code Playgroud)
入这个
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{x:Bind ViewModel.Items}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:ProjectItem">
<local:MyUserControl1 />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Page>
Run Code Online (Sandbox Code Playgroud)
<UserControl
x:Class="App1.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind Name}" />
<TextBlock Text="{x:Bind Description}" />
</StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
问题在于它甚至不编译,因为x:Bind
不知道上下文。
x:Bind如何涵盖此用例?
我建议在MyUserControl1.xaml.cs上为ProjectItem创建依赖项属性
public static readonly DependencyProperty ProjectItemProperty =
DependencyProperty.Register(
nameof(ProjectItem),
typeof(ProjectItem),
typeof(MyUserControl1),
null);
public ProjectItem ProjectItem
{
get => (ProjectItem)GetValue(ProjectItemProperty);
set => SetValue(ProjectItemProperty, value);
}
Run Code Online (Sandbox Code Playgroud)
然后在XAML上,绑定ProjectItem Dependency属性的属性:
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind ProjectItem.Name, Mode=OneWay}" />
<TextBlock Text="{x:Bind ProjectItem.Description, Mode=OneWay}" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
然后在MainPage.xaml上传递“ ProjectItem”集合项。
<DataTemplate x:DataType="local:ProjectItem">
<local:MyUserControl1 ProjectItem="{x:Bind}"/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)