6

我有一個進度條,我想根據布爾值更改顏色; true爲綠色,false爲紅色。我有看起來應該工作的代碼(當我將它綁定到文本框時它會返回正確的值),但當它是進度條的顏色屬性時不會返回正確的值。該轉換器被定義爲這個(在App.xaml.cs,因爲我想在任何地方訪問它):IValueConverter不適用於SolidColorBrush

public class ProgressBarConverter : System.Windows.Data.IValueConverter 
{ 
    public object Convert(
     object o, 
     Type type, 
     object parameter, 
     System.Globalization.CultureInfo culture) 
    { 
     if (o == null) 
      return null; 
     else 
      //return (bool)o ? new SolidColorBrush(Colors.Red) : 
      //     new SolidColorBrush(Colors.Green); 
      return (bool)o ? Colors.Red : Colors.Green; 
    } 

    public object ConvertBack(
     object o, 
     Type type, 
     object parameter, 
     System.Globalization.CultureInfo culture) 
    { 
     return null; 
    } 
} 

我然後添加以下到的App.xaml(因此它可以是一個全球性的資源):

<Application.Resources> 
    <local:ProgressBarConverter x:Key="progressBarConverter" /> 
    <DataTemplate x:Key="ItemTemplate"> 
     <StackPanel> 
      <TextBlock Text="{Binding name}" Width="280" /> 
      <TextBlock Text="{Binding isNeeded, 
          Converter={StaticResource progressBarConverter}}" /> 
      <ProgressBar> 
       <ProgressBar.Foreground> 
        <SolidColorBrush Color="{Binding isNeeded, 
          Converter={StaticResource progressBarConverter}}" /> 
       </ProgressBar.Foreground> 
       <ProgressBar.Background> 
        <SolidColorBrush Color="{StaticResource PhoneBorderColor}"/> 
       </ProgressBar.Background> 
      </ProgressBar> 
     </StackPanel> 
    </DataTemplate> 
</Application.Resources> 

添加以下到MainPage.xaml中以顯示它們:

<Grid x:Name="LayoutRoot" Background="Transparent"> 
    <ListBox x:Name="listBox" 
      ItemTemplate="{StaticResource ItemTemplate}"/> 
</Grid> 

然後在MainPage.xaml.cs中,我定義一個類來保存數據,並將其綁定到列表框:

namespace PhoneApp1 
{ 
    public class TestClass 
    { 
     public bool isNeeded { get; set; } 
     public string name { get; set; } 
    } 

    public partial class MainPage : PhoneApplicationPage 
    { 
     // Constructor 
     public MainPage() 
     { 
      InitializeComponent(); 

      var list = new LinkedList<TestClass>(); 
      list.AddFirst(
           new TestClass { 
            isNeeded = true, name = "should be green" }); 
      list.AddFirst(
           new TestClass { 
            isNeeded = false, name = "should be red" }); 
      listBox.ItemsSource = list; 
     } 
    } 
} 

我附加了一個minimal working example,因此它可以被構建和測試。輸出的圖像是在這裏:

enter image description here

它從轉換爲文本框,但沒有進度條返回的值。當我運行調試器時,它甚至不會調用它。

感謝您的幫助!

+0

如果你的轉換器返回一個solidColorBrush並且你將它直接綁定到ProgressBar的Foreground屬性,它會不會起作用? – BigL 2012-01-11 16:17:49

+0

哇 - 工作。我仍然得到了xaml的支持,所以這不是我嘗試過的。如果你把這個作爲答案,我會接受它。感謝您的建議! – 2012-01-11 16:22:43

+0

@TaylorSouthwick將它作爲答案發布。我很高興我能幫上忙。 :) – BigL 2012-01-11 16:25:59

回答

3

嘗試修改您的轉換器以返回SolidColorBrush,然後直接綁定到您的ProgressBars Foreground屬性。