1

我在项目控件中有一堆文本块...我需要知道如何根据数据模型中的列表中的文本是否可用来为文本块中的文本加下划线..

对我来说听起来很简单......但自从过去 8 小时以来我一直在谷歌搜索......

我可以为此目的使用数据触发器和值转换器吗?如果是,那么我该如何执行 viewModel 中的方法(帮助我检查给定文本是否存在于数据模型列表中的方法)......

即使我使用条件模板......我如何访问位于我的模型中的列表(视图模型可以获取它......但是我如何访问视图模型?)..

这应该是一件相当容易的事情......我真的错过了一些非常简单的东西吗?:)

我正在为我的应用程序遵循 MVVM 模式..

4

1 回答 1

1

一种方法是使用 multivalueconverter,它是一个实现IMultiValueConverter. 多值转换器允许您绑定到多个值,这意味着您可以获得对视图模型和值转换器中文本TextBlock的引用。

假设您的 viewmodel 有一个调用方法,该方法GetIsUnderlined返回 true 或 false 指示文本是否应该加下划线,您的 valueconverter 可以按照以下方式实现:

class UnderlineValueConverter : IMultiValueConverter
{
    #region IMultiValueConverter Members

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var viewmodel = values[0] as Window1ViewModel;
        var text = values[1] as string;
        return viewmodel.GetIsUnderlined(text) ? TextDecorations.Underline : null;
    }

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

    #endregion
}

您可以通过以下方式将此 valueconverter 用于 a TextBlock

<Grid x:Name="grid1" >
    <Grid.Resources>
        <local:UnderlineValueConverter x:Key="underlineValueConverter" />
    </Grid.Resources>

    <TextBlock Text="Blahblah">
        <TextBlock.TextDecorations>
            <MultiBinding Converter="{StaticResource underlineValueConverter}">
                <Binding /> <!-- Pass in the DataContext (the viewmodel) as the first parameter -->
                <Binding Path="Text" RelativeSource="{RelativeSource Mode=Self}" /> <!-- Pass in the text of the TextBlock as the second parameter -->
            </MultiBinding>
        </TextBlock.TextDecorations>
    </TextBlock>
</Grid>
于 2010-07-05T14:08:40.363 回答