ContentStringFormat绑定不会在propertychange上刷新

时间:2017-08-05 21:37:37

标签: c# .net wpf mvvm data-binding

我有一个问题导致标签在其内容没有变化但其格式有效时会刷新。 ContentStringFormat属性绑定到viewmodel并且通知属性更改,但标签没有更新,请在代码中找到最小的复制示例以及准备编译/运行的项目来演示问题。< / p>

下载项目:https://www.dropbox.com/s/rjs1lot09uc2lgj/WPFFormatBindingRefresh.zip?dl=0

XAML:

<StackPanel>
    <Label Content="{Binding FirstLabelContent}"></Label>
    <Label Content="{Binding SecondLabelContent}" ContentStringFormat="{Binding SecondLabelFormatContent}"></Label>
    <Button Click="Button_Click">Add "test" to all bound elements</Button>        
</StackPanel>

代码背后:

    public event PropertyChangedEventHandler PropertyChanged = (a,b)=> { }; // empty handler avoids checking for null when raising

    public string FirstLabelContent { get; set; } = "First Label";
    public string SecondLabelContent { get; set; } = "Second";
    public string SecondLabelFormatContent { get; set; } = "{0} Label";

    void PropertyChange(string PropertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        FirstLabelContent += " TEST";
        SecondLabelFormatContent += " TEST";
        PropertyChange("FirstLabelContent"); // First label correctly updates
        PropertyChange("SecondLabelFormatContent"); // Second label doesn't update, expected behavior is changing the format string should cause an update
    }

1 个答案:

答案 0 :(得分:1)

Label不支持通过绑定刷新ContentStringFormat

你可以使用这样的多转换器:

public class MultiConverter2 : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string SecondLabelContent = values[0] as string;
        string SecondLabelFormatContent = values[1] as string;

        return string.Format(SecondLabelFormatContent, SecondLabelContent);
    }

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

<强> XAML:

<StackPanel>
    <StackPanel.Resources>
        <local:MultiConverter2 x:Key="conv" />
    </StackPanel.Resources>
    <Label Content="{Binding FirstLabelContent}"></Label>
    <Label>
        <Label.Content>
            <MultiBinding Converter="{StaticResource conv}">
                <Binding Path="SecondLabelContent" />
                <Binding Path="SecondLabelFormatContent" />
            </MultiBinding>
        </Label.Content>
    </Label>
    <Button Click="Button_Click">Add "test" to all bound elements</Button>
</StackPanel>