我想写一个代表水箱的自定义silverlight控件。它有两个依赖项属性,liquidLevel和liquidCapacity,我想将这两个参数和gradientBrush一起传递给一个转换器。这个想法是,转换器将根据液位和容量进行计算,并调整刷子上的梯度停止位置,以使液体上升和下降。访问IvalueConverter |中的用户控件属性silverlight 4
我的坦克有一个“窗口”,这仅仅是一个矩形和gradientBrush,到目前为止,我得到这个
我的控制模板
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MoreControls;assembly=MoreControls"
xmlns:assets="clr-namespace:MoreControls.Assets">
<LinearGradientBrush x:Name="LiquidLevelTankWindow" StartPoint="0.469,0.997" EndPoint="0.487,0.013">
<GradientStop Color="#FF1010F1" Offset="0.0"/>
<GradientStop Color="#FF5555FB" Offset="0.55"/>
<GradientStop Color="#FFE4E4F1" Offset="0.6"/>
<GradientStop Color="#FFFAFAFD" Offset="1"/>
</LinearGradientBrush>
<assets:LiquidLevelBrushConverter x:Name="LiquidLevelBrushConverter" levelBrush="{StaticResource LiquidLevelTankWindow}"/>
<Style x:Key="Liquid" TargetType="local:LiquidTank">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:LiquidTank">
// * parts of the control here *
// the part of the control im interested in
<Rectangle x:Name="TankWindow" Width="32.3827" Height="64" Canvas.Left="27" Canvas.Top="42" Stretch="Fill" StrokeLineJoin="Round" Stroke="#FF000310"
Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=LiquidLevel, Converter={StaticResource LiquidLevelBrushConverter}}" />
// * rest of control template *
使用XAML控制(最终我想绑定这些性质)
<local:LiquidTank Style="{StaticResource Liquid}" LiquidCapacity="100" LiquidLevel="50"/>
和变换器
public class LiquidLevelBrushConverter : IValueConverter
{
public LinearGradientBrush levelBrush { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//I can access the liquid level parameter here
double level = 0;
double.TryParse(value.ToString(), out level);
GradientStopCollection gsc = levelBrush.GradientStops;
//some logic to alter gradient stops
return null;
}
我现在所在的位置是我想从我的转换器访问第二个控制属性liquidCapacity,以便我可以计算已满的坦克百分比。我已经尝试通过作为转换器参数通过liquidCapacity,但如果这是可能的,我不能弄清楚语法(我很新,silverlight)。
现在我已经有了这么远的想法我可以创建一个名为fillpercentage的独立属性,并在最终的viewmodel中执行这个计算,但是数据将在那里组织的方式非常肯定我会有一个整体如果我尝试这个新的挑战。对我来说,能够对xaml中的液体容量进行硬编码并将液位绑定到视图模型似乎更易于管理。视图模型将从数据库中抽取一些值并将其转换为可观察的字典,其中一个属于液位级别,因此,我认为将liquidlevel直接绑定到可观察字典,而不是尝试并转换它绑定到视图模型中的“fillpercentage”。
另外我很顽固,为了我的教育兴趣,有没有人知道我是否有可能做到。如果是这样,那么正确的方式呢?
欢呼,这个想法适合我 –