我在VisualStateMenager中绑定到此对象时遇到问题。我有XAML结构:
<DataTemplate x:Key="MenuItem">
<Border
x:Name="myItem"
Background="{StaticResource BackgroundColor}">
<StackPanel>
<TextBlock Text="{Binding HeaderText}" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="my">
<VisualState x:Name="active">
<Storyboard>
<ColorAnimation
Storyboard.TargetName="myItem"
Storyboard.TargetProperty="Background.Color"
To=" --- BIND TO THIS OBJECT COLOR PROPERTY ---"
//To="{Binding Color}" NOT WORK
//To="{Binding Color, ElementName=myItem}" NOT WORK
//To="red" WORKS
Duration=" 0:0:0.1"/>
</Storyboard>
</VisualState>
...
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</DataTemplate>
DataTemplate的DataContext必须正确,因为绑定表达式:{Binding HeaderText}和{Binding Text}工作正常。在同一个DataContext中,我还有一个属性“Color”:
public string HeaderText { get; set; }
public string Text { get; set; }
public string Color { get; set; }
我想在动画中将“Color”绑定到“ColorAnimation.To”,但不知怎的,我丢失了我的dataContext,并收到错误:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:路径=颜色;的DataItem = NULL; target元素是'ColorAnimation'(HashCode = 60716890); target属性为'To'(类型'Nullable`1')
另外值得一提的是其他一切都很好,尤其是状态变化。因为如果我从ColorAnimation中删除Binding,例如写入To =“red”。动画有效。
答案 0 :(得分:0)
当你指定&#34; Red&#34;时,你需要一个从string到SolidColorBrush ....的转换器。它使用enumerator
你可以使用这个课程
public class StringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var strValue = value as string;
if (string.IsNullOrEmpty(strValue)) return null;
Color color = Colors.Transparent;
try
{
color = (Color)ColorConverter.ConvertFromString(strValue);
}
catch
{
}
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
var color = (Color)value;
if (color == null) return Colors.Transparent.ToString();
return color.ToString();
}
catch
{
return Colors.Transparent.ToString();
}
}
}