数据模板通过转换器绑定网格背景



我有一个问题,有一段时间的数据绑定,改变了网格的颜色,不知何故它不工作。我在转换器中设置了一个断点,应用程序击中了它,但是网格的背景颜色仍然没有改变,它保持不变,因为没有定义背景颜色…

下面是我的代码:
<ListView ItemsSource="{Binding ResultsUserControls}"
          Background="{x:Null}"
          BorderBrush="{x:Null}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <Grid Width="200"
            Height="70"
            Background="{Binding CurrentResult,Converter={StaticResource crawlerTypeToResultColorConverter}}">
        <Label Content="{Binding .CurrentResult.SourceUrl}" />
      </Grid>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

和转换器:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Brushes.Red;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Binding.DoNothing;
    }

我认为这应该是

public object Convert(object value, Type targetType, object parameter, 
                      System.Globalization.CultureInfo culture)
{
    return new SolidColorBrush(Colors.Red);
}
public object ConvertBack(object value, Type targetType, object parameter, 
                          System.Globalization.CultureInfo culture)
{
    return Binding.DoNothing;
}

我已经修改了你的代码,你的代码应该可以工作了。作为实验,从Background:

的绑定中删除currenresult
<Grid Width="200" Height="70" Background="{Binding Converter={StaticResource crawlerTypeToResultColorConverter}}">

我想你现在会看到你的红色背景。我注意到,如果XAML解析器找不到要绑定到的属性(因为它拼写错误或根本不存在),它就不会进行转换。我猜XAML解析器无法在项目上找到CurrentResult。

最新更新