在我的Page.Resources中,我有DataTamplate:
<DataTemplate x:Key="gridviewQuestStyle">
<Button Content="{Binding QuestNumb}" Style="{StaticResource buttonQuestStyle}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="questionStates">
<VisualState x:Name="Right">
<Storyboard>
<ColorAnimation Storyboard.TargetName="BackgroundBrush" Storyboard.TargetProperty="Color" To="LightGreen" />
</Storyboard>
</VisualState>
<VisualState x:Name="Wrong">
<Storyboard>
<ColorAnimation Storyboard.TargetName="BackgroundBrush" Storyboard.TargetProperty="Color" To="Red" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Button.Background>
<SolidColorBrush x:Name="BackgroundBrush" Color="Black"/>
</Button.Background>
</Button>
</DataTemplate>
然后我创建网格视图:
<GridView Grid.Row="0" x:Name="GridView_ButtonsQuest"
ItemTemplate="{StaticResource gridviewQuestStyle}"
ItemsSource="{Binding Questions}" >
</GridView>
问题是一个列表:
public class Question
{
public string QuestNumb { get; set; }
public string QuestText { get; set; }
}
我的应用程序的逻辑是:
if(isAnswerRight)
{
VisualStateManager.GoToState(???, "Right", false);
}
else
{
VisualStateManager.GoToState(???, "Wrong", false);
}
请解释一下,我在GoToState方法的第一个参数中需要什么?
如果 VisualState 开关出现在页面或用户控件的.cs文件中(而不是在 MVVM 视图模型中)。将名称属性应用于网格视图
<GridView Grid.Row="0" x:Name="GridView_ButtonsQuest"
ItemTemplate="{StaticResource gridviewQuestStyle}"
ItemsSource="{Binding Questions}"
x:Name="myStateChanges" >
</GridView>
然后把它贴在 GoToState() 方法中。
if(isAnswerRight)
{
VisualStateManager.GoToState(this.myStateChanges, "Right", false);
}
else
{
VisualStateManager.GoToState(this.myStateChanges, "Wrong", false);
}
在列表视图上遇到了同样的问题。可以使用 ItemContainerGenerator 和 VisualTreeHelper 访问模板内的控件
foreach (var item in GridView_ButtonsQuest.Items)
{
var gridItem = (GridViewItem)MyList.ItemContainerGenerator.ContainerFromItem(item);
var wrap1 =VisualTreeHelper.GetChild(gridItem , 0);
var wrap2 = VisualTreeHelper.GetChild(wrap1 , 0);
...
我使用 xmalspy 来找出控件包装了多少层。应该可以构建一些执行此递归的东西。
我遇到的下一个问题是你不能将GoToState与网格或按钮一起使用。但是有人花时间开发了一个支持它的ExtendedVisualStateManager,请参阅 http://social.msdn.microsoft.com/Forums/en-GB/winappswithcsharp/thread/24dc19ff-15ed-4170-b3c3-d313728b642b
然后你可以写 ExtendedVisualStateManager.GoToElementState(...)