0
我創建了我自己的CustomSlider
(UserControl
)。請參見下面的代碼:難以依賴屬性
後面的代碼:
public partial class CustomSlider : UserControl, INotifyPropertyChanged
{
public CustomSlider()
{
InitializeComponent();
this.Loaded += CustomSlider_Loaded;
}
public static readonly DependencyProperty PositionProperty;
static CustomSlider()
{
PositionProperty = DependencyProperty.Register("Position", typeof(double), typeof(CustomSlider), new FrameworkPropertyMetadata());
}
public double Position
{
get
{
return (double)GetValue(PositionProperty);
}
set
{
SetValue(PositionProperty, value);
NotifyPropertyChanged("Position");
}
}
double length = 0;
void CustomSlider_Loaded(object sender, RoutedEventArgs e)
{
track.DataContext = this;
}
public double MaxValue { get; set; }
public event EventHandler ValueChangedManually;
//Changing the position manually
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
length = this.Width;
if (Double.IsNaN(this.Width))
length = this.ActualWidth;
Point p = Mouse.GetPosition(this);
try
{
//Position = p.X; // this didn't work too
this.SetValue(PositionProperty, p.X);
}
catch (Exception ex)
{
//test
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
XAML:
<Grid>
<Border BorderThickness="1" Background="White" BorderBrush="Blue" MouseLeftButtonDown="Border_MouseLeftButtonDown"/>
<Label Name="track" Background="#FF4250D8" Width="{Binding Path=Position, Mode=TwoWay}" HorizontalAlignment="Left" MouseLeftButtonDown="Border_MouseLeftButtonDown" />
</Grid>
我在形式創造了我控制的新實例,並試圖改變Position
(我的控制屬性之一)通過點擊頂部的CustomSlider
。它改變了我的預期。然後我試着用DoubleAnimation
來做到這一點。它也能正常工作。問題是我無法通過點擊CustomSlider
頂部Position
更改Position
與DoubleAnimation
更改Position
。以下是動畫代碼:
private void Button_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation anim = new DoubleAnimation();
anim.From = 0;
anim.To =350;
anim.Duration = TimeSpan.FromMilliseconds(1000);
slider.BeginAnimation(CustomSlider.PositionProperty, anim);
}
我的DependecyProperty
有什麼問題嗎?請幫助解決這個問題。 謝謝,
只是出於好奇,你的滑塊做什麼,默認的不能? – 2013-05-07 21:09:40
@ChrisW。我正在製作播放音頻的應用程序。我需要顯示當前正在播放的位置。用戶需要能夠手動更改它。默認滑塊完全一樣,但我的客戶需要不同類型的UI。 – Dilshod 2013-05-07 21:12:38
閱讀[依賴屬性值優先順序](http://msdn.microsoft.com/en-us/library/ms743230.aspx)。動畫是重中之重。在您的處理程序中,您設置了被視爲「本地」的屬性,這是動畫下的兩個訂單。所以,你需要在設置屬性之前停止動畫。此外,您不需要依賴項屬性中的更改通知。最後,要改變UI使用'ControlTemplate'而不是滾動自己的。 – XAMeLi 2013-05-07 21:15:17