gpt4 book ai didi

c# - SetCurrentValue myLabel.BackgroundProperty 不破坏绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 13:58:46 26 4
gpt4 key购买 nike

我有三个文本框和一个标签。使用 Multiconverter 将标签绑定(bind)到文本框中的文本。

XAML:

<Label Name="lbl" Content="Label" HorizontalAlignment="Left" Margin="336,128,0,0" VerticalAlignment="Top" Height="57" Width="93">
<Label.Background>
<MultiBinding Converter="{StaticResource converta}">
<Binding ElementName="R" Path="Text" Mode="TwoWay" />
<Binding ElementName="G" Path="Text" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" />
<Binding ElementName="B" Path="Text" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" />
</MultiBinding>

</Label.Background>
</Label>
<TextBox Name="R" HorizontalAlignment="Left" Height="23" Margin="250,214,0,0" TextWrapping="Wrap" Text="255" VerticalAlignment="Top" Width="120"/>
<TextBox Name="B" HorizontalAlignment="Left" Height="23" Margin="271,242,0,0" TextWrapping="Wrap" Text="255" VerticalAlignment="Top" Width="120"/>
<TextBox Name="G" HorizontalAlignment="Left" Height="23" Margin="155,275,0,0" TextWrapping="Wrap" Text="255" VerticalAlignment="Top" Width="120"/>

转换器

class converter : IMultiValueConverter
{

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{

return new System.Windows.Media.SolidColorBrush(Color.FromRgb(System.Convert.ToByte((values[0] as string)), System.Convert.ToByte((values[1] as string)), System.Convert.ToByte((values[2] as string))));

}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
byte R = (value as System.Windows.Media.Color?).Value.R;
byte G = (value as System.Windows.Media.Color?).Value.G;
byte B = (value as System.Windows.Media.Color?).Value.B;
return new string[] {System.Convert.ToString(R),System.Convert.ToString(G),System.Convert.ToString(B)};

}
}

(显然,在现实世界中我会添加验证和类型检查)。

现在我想添加一个按钮来设置标签背景,像这样简单:

    lbl.Background= new SolidColorBrush(Color.FromRgb(
System.Convert.ToByte(121),
System.Convert.ToByte(43),
System.Convert.ToByte(15)));

显然,它打破了绑定(bind)。所以我尝试:

    SetCurrentValue(lbl.BackgroundProperty, 
new SolidColorBrush(
Color.FromRgb(System.Convert.ToByte(121),
System.Convert.ToByte(43),
System.Convert.ToByte(15))));

但是 VS 提示说

Member 'System.Windows.Controls.Control.BackgroundProperty' cannot be accessed with an instance reference; qualify it with a type name instead

如何在不破坏绑定(bind)的情况下在代码中设置标签背景的值?

注意:这是WPF,.Net 4.5

最佳答案

错误是 self 描述的,它告诉你 lbl.BackgroundProperty 不能那样设置。以下是执行此操作的正确方法。

        lbl.SetCurrentValue(BackgroundProperty,
new SolidColorBrush(Color.FromRgb(System.Convert.ToByte(121),
System.Convert.ToByte(43),
System.Convert.ToByte(15))));

关于c# - SetCurrentValue myLabel.BackgroundProperty 不破坏绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475851/

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