开发者

WPF style of item based on parent's properties

I have a view model with properties

IEnumerable<Page> Pages { get; }
Page CurrentPage { get; }

And I have XAML bindings like so:

<ItemsControl ItemsSource="{Binding Pages}" Margin="10">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <BulletDecorator>
                <BulletDecorator.Bullet>
                    <TextBlock Text=" •  " FontWeight="Heavy" />
                </BulletDecorator.Bullet>

                <TextBlock Text="{Binding Title}" FontWeight="{Binding ????, Converter={StaticResource BTFWC}}" />
            </BulletDecorator>
        </DataTemplate>
    </Item开发者_JS百科sControl.ItemTemplate>
</ItemsControl>

The view model has properties Pages and CurrentPage. I want the text of the Page in the list to be bold whenever that page is set as CurrentPage on the view model. What do I have to put in place of "????" in the XAML above to achieve that purpose? I'd like to avoid having a "IsCurrent" property on the Page itself, since I feel like it's not its responsibility to know whether it's the current page or not.

P.S.: The BTFWC is a "Boolean To Font Weight Converter", if you wondered.


I hope that Page is not a System.Windows.Controls.Page because it cannot be placed into ItemsControl.

If it is not, you may create IMultiValueConverter which accepts a Page of an item and the CurrentPage:

public class IsCurrentToFontWeightConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Length == 2 && values[0] == values[1])
        {
            return FontWeights.Bold;
        }

        return FontWeights.Normal;
    }

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

and use it in the following Binding:

<TextBlock Text="{Binding Title}">                            
    <TextBlock.FontWeight>
        <MultiBinding>
            <MultiBinding.Converter>
                <local:IsCurrentToFontWeightConverter/>
            </MultiBinding.Converter>
            <Binding Path="."/>
            <Binding Path="DataContext.CurrentPage"
                        RelativeSource="{RelativeSource AncestorType={x:Type ItemsControl}}"/>
        </MultiBinding>
    </TextBlock.FontWeight>
</TextBlock>


Try this

<TextBlock Text="{Binding Title}" FontWeight="{Binding DataContext.CurrentPage,
    Converter={StaticResource BTFWC},RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type ItemsControl}}}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜