2010-06-24 123 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