我正在尝试通过通过转换器修改的双重属性将颜色绑定到我的 UserControl
背景。但是,由于某种原因,它行不通。如果我的转换函数有断点,它永远不会断裂。
有一个按钮触发从单击文本框设置PaceLabel.Speed
属性的函数。该部分正常工作,因此我没有在此处复制代码的那部分粘贴。
这是我代码的一部分:
owncomponent.xaml
<UserControl x:Class="OwnComponentNs.OwnComponent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OwnComponentNs"
mc:Ignorable="d" Width="Auto">
...
<UserControl.Resources>
<local:DoubleToSolidColorBrushConverter x:Key="doubleToBackgroundConverter" />
</UserControl.Resources>
<UserControl.Background>
<Binding ElementName="paceLabel" Path="Speed" Converter="{StaticResource doubleToBackgroundConverter}" />
</UserControl.Background>
<local:PaceLabel x:Name="paceLabel" />
...
owncomponent.xaml.cs
namespace OwnComponentNs
{
public partial class OwnComponent : UserControl
{
public OwnComponent()
{
InitializeComponent();
}
}
public class DoubleToSolidColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
byte val = System.Convert.ToByte((double)value);
return new SolidColorBrush(Color.FromRgb(val, val, val));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
public class PaceLabel : Label
{
private double _duration = 0;
private double _distance = 0;
private double _speed = 0;
public double Duration
{
get { return _duration; }
set { _duration = value; UpdateText(); }
}
public double Distance
{
get { return _distance; }
set { _distance = value; UpdateText(); }
}
public double Speed
{
get { return _speed; }
set { _speed = value; }
}
public PaceLabel()
{
UpdateText();
}
private void UpdateText()
{
double pace = Distance == 0 ? 0 : TimeSpan.FromHours(Duration).TotalMinutes / Distance;
Content = Math.Round(pace, 2) + " min/km";
}
}
}
如果您需要更多详细信息,请告诉我。预先感谢!
您需要您的pacelabel类来实现接口:inotifyPropertychanged,
或将其属性重写为depentencyProperties。
PaceLabel
应该实现INotifyPropertyChanged
,PaceLabel.Speed
应触发该事件。