在contentcontrol中绑定datatemplate的背景

时间:2017-10-17 16:53:13

标签: c# wpf xaml

我正在尝试绑定TextBox的背景颜色并使用转换器。但是,由于TextBox位于DataTemplateContentControl,我无法确定正确的绑定。

除非我将绑定路径从DebuggingConverter设置为Path=StateColor

,否则Path=.不会触发

这是xaml:

<GridViewColumn Header="Value" Width="{Binding SelectedDeviceCol2, Source={x:Static properties:Settings.Default}, Mode=TwoWay}" >
<GridViewColumn.CellTemplate>
    <DataTemplate>
        <ContentControl Content="{Binding Path=Value, Mode=TwoWay}" IsEnabled="{Binding Path=ReadOnly, Converter={StaticResource readOnlyToEnabledConverter}}">
            <ContentControl.Resources>
                <DataTemplate DataType="{x:Type viewModels:VMDeviceCommand}">
                    <Button Content="{Binding Name}" Height="24" IsEnabled="True" Click="Button_Click_GetObjectProperty"/>
                </DataTemplate>
                <DataTemplate DataType="{x:Type System:DateTime}">
                    <DatePicker SelectedDate="{Binding Path=.}"
                            SelectedDateFormat="Short"
                            FirstDayOfWeek="Monday"  
                            IsTodayHighlighted="True" >
                    </DatePicker>
                </DataTemplate>
                <DataTemplate DataType="{x:Type System:String}">
                    <TextBox Text="{Binding Path=.}" TextChanged="TextBox_OnTextChanged">
                        <TextBox.Background>
                            <SolidColorBrush Color="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=StateColor, Converter={StaticResource DebuggingConverter}}"/>
                        </TextBox.Background>
                    </TextBox>
                </DataTemplate>                 
                <DataTemplate DataType="{x:Type System:UInt16}">
                    <xctk:IntegerUpDown  Text="{Binding Path=.}" ValueChanged="UpDownBase_OnValueChanged" >
                    </xctk:IntegerUpDown>
                </DataTemplate>
                <DataTemplate DataType="{x:Type System:Boolean}">
                    <CheckBox IsChecked="{Binding Path=.}" Click="CheckBox_Click"/>
                </DataTemplate>
            </ContentControl.Resources>
        </ContentControl>
    </DataTemplate>
</GridViewColumn.CellTemplate>

1 个答案:

答案 0 :(得分:1)

ContentControl没有StateColor属性,因此Binding永远不会得到它的值,也没有任何东西可以传递给转换器。

如果ContentControl的DataContext具有StateColor属性,那很容易:

<SolidColorBrush 
    Color="{Binding DataContext.StateColor, RelativeSource={RelativeSource AncestorType=ContentControl}, Converter={StaticResource DebuggingConverter}}"
    />