gpt4 book ai didi

silverlight - IValueConverter 不适用于 SolidColorBrush

转载 作者:行者123 更新时间:2023-12-04 15:36:18 24 4
gpt4 key购买 nike

我有一个进度条,我想根据 bool 值更改颜色; true 为绿色,false 为红色。我的代码看起来应该可以工作(当我将它绑定(bind)到文本框时它返回正确的值),但当它是进度条的颜色属性时却不行。转换器是这样定义的(在 App.xaml.cs 中,因为我想在任何地方访问它):

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 中,我定义了一个类来保存数据并将其绑定(bind)到 listBox:
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

它从转换器返回文本框的值,但不返回进度条。当我运行调试器时,它甚至没有调用它。

谢谢你的帮助!

最佳答案

尝试修改您的转换器以返回 SolidColorBrush然后直接绑定(bind)到你的ProgressBars前台属性。

关于silverlight - IValueConverter 不适用于 SolidColorBrush,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8822334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com