2010-06-24 141 views
0

我试图将一个资源对象的属性绑定到一个控件(一个组合...) - 该东西似乎在设计器中工作,但它不工作运行。 只使用一个简单的页面,只有一个按钮和一个组合 - 资源部分:Silverlight:绑定资源对象的属性

<UserControl.Resources> 
    <LinearGradientBrush x:Key="myBrush" EndPoint="1,0.5" StartPoint="0,0.5"> 
     <GradientStop Offset="0" Color="{Binding ElementName=w_comboColor, Path=SelectedItem.Content}" /> 
     <GradientStop Offset="1" Color="White" /> 
    </LinearGradientBrush> 
</UserControl.Resources> 

部件部分:

<Button Name="w_button" Grid.Row="0" Width="200" Content="Button" Height="60" HorizontalAlignment="Center" 
     Margin="2" VerticalAlignment="Center" Background="{Binding Source={StaticResource myBrush}}"> 
</Button> 

<ComboBox Grid.Row="1" Height="24" HorizontalAlignment="Stretch" Margin="2" 
      Name="w_comboColor" VerticalAlignment="Center" SelectedIndex="1" > 
    <ComboBox.Items> 
     <ComboBoxItem Content="Red" /> 
     <ComboBoxItem Content="Blue" /> 
     <ComboBoxItem Content="Green" /> 
    </ComboBox.Items> 
</ComboBox> 

改变组合的SelectedIndex属性的值,在设计师使按钮背景改变其背景颜色(如预期)。 如果我运行该示例,什么都不工作: - \

我试图强制UserControl的DataContext和其他东西 - 什么也没有发生:在运行时绑定被打破。 有什么建议吗?

回答

0

您需要在GradientStop.Color绑定中添加一个ValueConverter,将其从string转换为Color。您当前的绑定尝试将string分配给Color属性。我会想象设计师会为你做类型转换,就像在XAML中完成一样,但是这不会在运行时发生。您将需要一个转换是这样的:

public class ColorConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if(value == "Red") 
      return Colors.Red; 
     else if(value == "Blue") 
      return Colors.Blue; 
     else if(value == "Green") 
      return Colors.Green; 
    } 
} 

这绝对不是一个完整的转换器,但它应该指向你在正确的方向。

+0

嗨斯蒂芬,非常感谢您的回答。 其实我已经尝试添加到Gradient.Stop绑定的转换器,但它被完全忽略。使用转换器的唯一方法是将Gradient.Stop.Color绑定到后面代码中的Color DP,然后使用Converter将Combo绑定到该DP,这当然会将字符串转换为Color。 无论如何,这是一个“解决方法” - 当然,它运作良好:-)但我只是想了解如何在“纯XAML”中完成这项工作,因为它可能是一个很好的其他方面的“样本”我们的基础设施给我们的客户。 – 2010-06-25 08:49:53

0

当这些对象直接从DependencyObject继承(如GradientStop一样)时,资源对象上的绑定将被忽略。绑定对从FrameworkElement继承的资源对象起作用。

+0

最新评论回复,但 - 您可以用微软提供的资源回复该声明吗?我似乎无法找到任何参考。谢谢Jarda。 – TravisWhidden 2012-03-13 03:41:30