2013-03-18 40 views
2

我有一个滑块,它的属性绑定到依赖项属性。我需要知道用户是否已通过GUI更改了值。不幸的是,这个滑块的值经常通过代码来改变,当发生这种情况时,“Value_Changed”事件触发。用户是否已通过用户界面更改了值,还是由依赖项属性更改了?

我知道有两种方法去解决此问题:

  1. 创建一个布尔值,并更改值,之后将其更改为false,然后检查这个布尔之前,每一次改变为真正的代码在Value_Changed事件中。
  2. 将按键,click和dragstop事件连接到滑块。

我只是想知道是否有更好的方法知道用户是否已经通过UI更改了值?

+0

怎么样的鼠标按下和KEYDOWN事件?当用户通过鼠标或键盘做某事时,两个事件都会发生。 – 2013-03-18 12:56:26

+0

您可以检查滑块是否有焦点。如果确实如此,则该值将从UI中更改。但是,这将取决于将代码从后面更改为滑块。 – AbZy 2013-03-18 12:58:55

回答

2

我会做这种方式:

public bool PositionModifiedByUser 
{ /* implement IPropertyChanged if need to bind to this property */ } 

// use this property from code 
public double Position 
{ 
    get { return m_position ; } 
    set { SetPropertyValue ("PositionUI", ref m_position, value) ; 
      PositionModifiedByUser = false ; } 
} 

// bind to this property from the UI 
public double PositionUI 
{ 
    get { return m_position ; } 
    set { if (SetPropertyValue ("PositionUI", ref m_position, value)) 
      PositionModifiedByUser = true ; } 
} 

SetPropertyValue是检查平等和激发属性更改通知,如果该值实际上改变帮手。

+0

问题是,当控件初始化为初始值时,PositionUI仍会调用为我更改的值。 – David 2013-03-18 19:30:16

+0

对不起,我不明白你指的是什么情况。谁初始化控制?什么初始值?等等 – 2013-03-19 00:22:29

0

可能重复的问题。快速回答:

<Slider Thumb.DragCompleted="MySlider_DragCompleted" /> 

又见this post

+0

我已经看到了,请参阅第2点。从答案:“不幸的是,这只会在拖动时被解雇,因此您需要分别处理其他点击和按键。” – David 2013-03-18 12:57:08

+0

你不想处理KeyPress? – David 2013-03-18 12:59:28

0

但是,从安东的回答是更好+1

[BindableAttribute(true)] 
public double Slider1Value 
{ 
    get { return slider1Value; } 
    set 
    { 
     // only bind to the UI so any call to here came from the UI 
     if (slider1Value == value) return; 
     // do what you were going to do in value changed here 
     slider1Value = value; 
    } 
} 

private void clickHalf(object sender, RoutedEventArgs e) 
{ 
    // manipulate the private varible so set is not called 
    slider1Value = slider1Value/2; 
    NotifyPropertyChanged("Slider1Value"); 
} 
相关问题