【发布时间】:2015-11-17 20:39:57
【问题描述】:
我有一个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>
这是这个 XAML 背后的类:
public sealed partial class MyPage : Page
{
public MyPage()
{
InitializeComponent();
ListView.ItemsSource = new List<MyListItem>()
{
new MyListItem("Title1", "SubTitle1"),
new MyListItem("Title2", "SubTitle2")
}
}
}
还有 MyListItem 类:
class MyListItem
{
public string MyProperty { get; set; }
public string MyOtherProperty { get; set; }
public MyListItem(string myProperty, string myOtherProperty)
{
MyProperty = myProperty;
MyOtherProperty = myOtherProperty;
}
}
有问题的最小项目:
【问题讨论】:
-
你的代码对我来说很好。
-
请提供MyListItem类代码
-
@VMaleev 编辑了我的问题