vrw*_*wim 2 wpf xaml binding listview uwp
我有一个ListView,填充了一个List<MyListItem>,我需要使用一个ControlTemplate能够在选择项目时更改效果.现在我的问题在其中{Binding MyProperty}无效ControlTemplate.如何访问MyListItem模板内部的属性?
我的XAML看起来像这样(简化):
<ListView
Name="ListView"
Grid.Column="1"
IsSwipeEnabled="False">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected">
<Storyboard>
<ColorAnimation Duration="0" Storyboard.TargetName="myColoredText" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="Orange"/>
</Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused">
<Storyboard>
<ColorAnimation Duration="0" Storyboard.TargetName="myColoredText" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="Red"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<!-- Here I have my custom layout, removed for readability -->
<TextBlock
Name="myColoredText"
Foreground="Green"
Text="{Binding MyProperty}"/><!-- This does not work -->
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>
Run Code Online (Sandbox Code Playgroud)
这是XAML背后的类:
public sealed partial class MyPage : Page
{
public MyPage()
{
InitializeComponent();
ListView.ItemsSource = new List<MyListItem>()
{
new MyListItem("Title1", "SubTitle1"),
new MyListItem("Title2", "SubTitle2")
}
}
}
Run Code Online (Sandbox Code Playgroud)
和MyListItem类:
class MyListItem
{
public string MyProperty { get; set; }
public string MyOtherProperty { get; set; }
public MyListItem(string myProperty, string myOtherProperty)
{
MyProperty = myProperty;
MyOtherProperty = myOtherProperty;
}
}
Run Code Online (Sandbox Code Playgroud)
有问题的最小项目:
XAM*_*eLi 12
在TextBox,使用:
Text="{Binding Content.MyProperty,
RelativeSource={RelativeSource TemplatedParent}}"
Run Code Online (Sandbox Code Playgroud)