gpt4 book ai didi

c# - ContentStringFormat 绑定(bind)不会在 propertychange 上刷新

转载 作者:行者123 更新时间:2023-12-03 10:33:21 29 4
gpt4 key购买 nike

我遇到了一个问题,导致标签在其内容不变但其格式发生变化时刷新。 ContentStringFormat 属性绑定(bind)到 View 模型并通知属性更改,但标签不会更新,请在下面找到代码中的最小复制示例以及准备编译/运行的项目来演示该问题。

下载项目: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
}

最佳答案

Label不支持刷新ContentStringFormat通过绑定(bind)。

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

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>

关于c# - ContentStringFormat 绑定(bind)不会在 propertychange 上刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45526615/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com