2014-04-08 15 views
1

我是binding的新手。我已將slider值綁定到我的控件的屬性,並且在更改滑塊值時我的控件屬性發生了更改。 現在,當我需要通過更改我的屬性值來更改滑塊值時,它不起作用。無法使用雙向綁定與我的控制

我修改了某些Internet源的xaml,但仍未獲得預期輸出。 任何人都可以幫我...

<Grid> 
    <cc:MyControl Name="mycntrl" ZoomPercentage="{Binding ElementName=slider,Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></cc:MyControl> 
    <Slider Name="slider" Margin="20,20,20,400" Minimum="100" Maximum="400"></Slider> 
</Grid> 

更新時間:

我後面的代碼爲我的ZoomPercentage依賴屬性低於

public double ZoomPercentage 
    { 
     get 
     { 
      return (double)GetValue(ZoomPercentageProperty); 
     } 
     set 
     { 
      SetValue(ZoomPercentageProperty, value); 
     } 
    } 

我的依賴登記

public static readonly DependencyProperty ZoomPercentageProperty = DependencyProperty.Register("ZoomPercentage", typeof(double), typeof(MyControl), new FrameworkPropertyMetadata(ZoomPercentagePropertyChanged)); 


public static void ZoomPercentagePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) 
    { 
     if (args.OldValue != null) 
     { 
      if ((double)args.NewValue != (double)args.OldValue) 
      { 
       MyControl mycontrol = obj as MyControl; 
       mycontrol .ZoomTo((int)((double)args.NewValue)); 
      } 
     } 
    } 

回答

1

您的ZoomPercentage屬性應實現爲Dependencyproperty 像這樣的事情

public class MyControl:UserControl 
{ 
    public MyControl() : base() { } 
    public double ZoomPercentage 
    { 
    get { return (double)this.GetValue(ZoomPercentageProperty); } 
    set { this.SetValue(ZoomPercentageProperty, value); } 
    } 
    public static readonly DependencyProperty ZoomPercentageProperty = DependencyProperty.Register(
    "ZoomPercentage", typeof(double), typeof(MyControl:),new PropertyMetadata(0)); 
} 

更多here

1

如果你想在UI綁定控件的數據代碼進行更改後更新,那麼你必須做一個兩件事情。一種選擇是在宣佈您的Value屬性的類中正確實施INotifyPropertyChanged interface

另一種是你Value財產申報作爲DependencyProperty,但你應該只真正做到這一點的代碼你WindowUserControl的背後,如果你使用的是視圖模型選擇第一種方法。這兩種方法的目的是爲了「插入」WPF通知框架,以便更新您的UI控件。請閱讀鏈接頁面瞭解更多信息。