简体   繁体   中英

wpf borderbrush binding in itemscontrol

I have a Border inside an ItemsControl which needs to get it's BorderBrush from a field called BorderColor in the ItemsSource (an Observable Collection).

<ItemsControl ItemsSource="{Binding ObsColOfThings}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Border BorderThickness="3" BorderBrush="{Binding BorderColor}">
                            <ContentPresenter Content="{Binding}" />
                        </Border>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border >
                <TextBlock Text="{Binding Text}" />
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The binding is working but the border brush is not.

I've also tried this and it doesn't work either despite the text working fine

<ItemsControl ItemsSource="{Binding Appointments}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="{Binding BorderColor" BorderThickness="3">
                <TextBlock Text="{Binding AppointmentDescription}" />
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Where am I going wrong?

It doesn't make sense to specify the ItemTemplate and the ContentPresenter's ContentTemplate of an ItemsControl at the same time, because the ItemTemplate effectively replaces the ContentTemplate.

Drop the entire ItemContainerStyle and write your ItemsControl like this:

<ItemsControl ItemsSource="{Binding ObsColOfThings}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderThickness="3" BorderBrush="{Binding BorderColor}">
                <TextBlock Text="{Binding Text}" />
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The type of the BorderColor property should be Brush :

public class Item
{
    public string Text { get; set; }
    public Brush BorderColor { get; set; }
}

and then it should of course be called BorderBrush , not BorderColor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM