1

我有一个清单MyItem。该对象表示具有某些属性的形状,例如宽度、高度和颜色。Alpha使用转换器,如果选择了我的对象(我不想更改不透明度),我正在尝试将填充颜色从 (255, r, g, b) 更改为 ( , r, g, b ) 。Alpha(double) 住在我的视图模型中。

我的问题是发送到转换器的两个值都设置为DependencyProperty.UnsetValue,无论我给它什么。如果我只指定Path我希望它绑定到我的视图模型,但它没有。显然,我在这里做错了什么。

问:我需要Alpha我的 viewmodel 和MyItemColorDataContext 的myitem(我假设在 MultiBinding 块内时它仍然是 DataContext)。我的Binding标签应该是什么样的?

XAML

<DataTemplate>
  <Grid>
    <Rectangle x:Name="myitem" Width="{Binding MyItemWidth}" Height="{Binding MyItemHeight}" />
  </Grid>
  <DataTemplate.Triggers>
    <MultiDataTrigger>
      <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding IsSelected}" Value="False"/>
      </MultiDataTrigger.Conditions>
      <Setter TargetName="myitem" Property="Fill">
        <Setter.Value>
          <!-- Simple binding works. WHAT is the difference?
          <SolidColorBrush>
            <SolidColorBrush.Color>
              <Binding Path="Color" />
            </SolidColorBrush.Color>
          </SolidColorBrush>
          -->
          <SolidColorBrush>
            <SolidColorBrush.Color>
              <!-- Change fill color if DataContext.Scale changes -->
              <MultiBinding Converter="{StaticResource DoubleToColorConverter}">
                <!-- wrong? -->
                <Binding Path="Alpha" />
                <!-- wrong? -->
                <Binding ElementName="myitem" Path="MyItemColor" />
              </MultiBinding>
            </SolidColorBrush.Color>
          </SolidColorBrush>
        </Setter.Value>
      </Setter>
    </MultiDataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>

转换器

public class DoubleToColorConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType,
        object parameter, CultureInfo culture)
    {
        // values[0] == DependencyProperty.UnsetValue
        // values[1] == DependencyProperty.UnsetValue

        return null; // New color
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
        object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

更新

我解决了。我必须寻找父控件(包含项目)才能访问我的视图模型。澄清这一点,为什么它是好/坏,就足以作为一个答案!我不完全明白发生了什么:)

<MultiBinding Converter="{StaticResource DoubleToColorConverter}">
  <Binding ElementName="myItemsControl" Path="DataContext.Alpha"/>
  <Binding Path="Color" />
</MultiBinding>

和...

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    if (values[0] == DependencyProperty.UnsetValue || values[1] == DependencyProperty.UnsetValue)
        return Colors.Transparent;
    ...
}
4

0 回答 0