我正在尝试将颜色绑定到我的UserControl
背景中,来自转换器修改的double属性。但是由于某种原因它不起作用。如果我在转换函数中有断点,它永远不会中断。
有一个按钮可以触发在单击时从文本框设置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";
}
}
}
如果您需要更多详细信息,请与我们联系。提前谢谢!
答案 0 :(得分:0)
您需要PaceLabel类来实现接口:INotifyPropertyChanged,
或者将其属性重写为DependencyProperties。
答案 1 :(得分:0)
PaceLabel
应该实现INotifyPropertyChanged
,而PaceLabel.Speed
应该触发该事件。