此代码适用于WPF,但不适用于Silverlight。
Silverlight中是否有任何变通方法可以让我将滑块值绑定到元素高度? Silverlight在这里有哪些限制?
感谢彼得为其他人解决这个问题:这里是the solution with online demo and downloadable code。
<UserControl x:Class="Second12.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
Width="300" Height="200">
<Grid Background="Tan">
<StackPanel>
<Canvas>
<Border Background="#2200ffff"
Canvas.Left="40"
Canvas.Top="30"
CornerRadius="5"
BorderBrush="Brown"
BorderThickness="1">
<Rectangle
Height="{Binding ElementName=theSlider, Path=Value}"
Width="50"/>
</Border>
</Canvas>
</StackPanel>
<Slider Name="theSlider" HorizontalAlignment="Left" Width="200" Cursor="Hand"/>
</Grid>
</UserControl>
答案 0 :(得分:4)
Silverlight 2中支持当前
在此期间你必须使用某种中间属性,这是一个完整的例子:
Page.xaml:
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<StackPanel x:Name="LayoutRoot" Background="AliceBlue">
<Slider x:Name="Slider1" Minimum="10" SmallChange="10"
LargeChange="20" Maximum="100"
Value="{Binding HelperValue, Mode=TwoWay}" Cursor="Hand"/>
<Rectangle x:Name="Rectangle1" Fill="Red"
Height="{Binding HelperValue, Mode=OneWay}" Width="100" />
</StackPanel>
</UserControl>
Page.xaml.cs:
using System;
using System.ComponentModel;
using System.Windows.Controls;
namespace SilverlightApplication1
{
public partial class Page : UserControl
{
BindingConduit<double> sliderToRect = new BindingConduit<double>(50.0);
public Page()
{
InitializeComponent();
LayoutRoot.DataContext = sliderToRect;
}
}
public class BindingConduit<T> : INotifyPropertyChanged where T : struct
{
private T helperValue;
public T HelperValue
{
get { return this.helperValue; }
set
{
if ((this.helperValue.Equals(value) != true))
{
this.helperValue = value;
this.RaisePropertyChanged("HelperValue");
}
}
}
public BindingConduit(T defaultValue)
{
HelperValue = defaultValue;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Slider的Value属性绑定到HelperValue并设置为TwoWay,Rectangle的Height绑定到同一属性但只需要OneWay。
正在从BindingConduit&lt; T&gt;的实例中读取HelperValue属性。在Page中创建的类名为sliderToRect。此实例设置为父StackPanel控件的DataContext。 Slider1的Value属性中的任何更改都会反映在Rectangle1的高度中,因为HelperValue属性会引发PropertyChanged事件。
BindingConduit&LT; T&GT;是我创建的实现INotifyPropertyChanged的自定义类,还允许您为HelperValue指定默认值(即Slider1的初始值和Rectangle1的高度(50.0))。