嗯,我正在做一個小項目,我發現沒有必要實現一個完整的MVVM。如何在不使用MVVM的情況下綁定DependencyProperty
我想綁定代碼背後的一些屬性,但無法設法使其工作。
重點是在後面的代碼中使用DependencyProperties和Binding。
我試圖按照這些鏈接和問題在SO:
Bind Dependency Property in codebehind WPF
How to: Create a Binding in Code
但它們與MVVM或者至少我無法適應的代碼我案件。
該示例應該非常簡單。
MainWindow.xaml
<Label Name="_lblCurrentPath"
Style="{StaticResource CustomPathLabel}"
ToolTip="{Binding CurrentPath}"
Content="{Binding CurrentPath, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"/>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
SetBindings();
}
#region Properties
public static readonly DependencyProperty CurrentPathProperty =
DependencyProperty.Register("CurrentPath", typeof(String), typeof(MainWindow), new PropertyMetadata(String.Empty, OnCurrentPathChanged));
public string CurrentPath
{
get { return (String)GetValue(CurrentPathProperty); }
set { SetValue(CurrentPathProperty, value); }
}
#endregion
#region Bindings
private void SetBindings()
{
// Label CurrentPath binding
Binding _currentPath = new Binding("CurrentPath");
_currentPath.Source = CurrentPath;
this._lblCurrentPath.SetBinding(Label.ContentProperty, _currentPath);
}
#endregion
#region Methods
private void Refresh()
{
MessageBox.Show("Refresh!");
}
private string Search()
{
WinForms.FolderBrowserDialog dialog = new WinForms.FolderBrowserDialog();
WinForms.DialogResult _dResult = dialog.ShowDialog();
switch(_dResult)
{
case WinForms.DialogResult.OK:
CurrentPath = dialog.SelectedPath;
break;
default:
break;
}
return CurrentPath;
}
#endregion
#region Events
private static void OnCurrentPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MainWindow instance = d as MainWindow;
instance.Refresh();
}
public void OpenSearchEclipsePath(object sender, RoutedEventArgs e)
{
CurrentPath = Search();
}
public void RefreshEclipsePath(object sender, RoutedEventArgs e)
{
Refresh();
}
任何想法?
。如果這是一個不好的做法,我應該使用MVVM評論,歡迎使用。
。也......與Command
財產有關。在這種情況下,我不想使用MVVM方法,註冊事件更好嗎?我發現使用自定義命令綁定有點乏味。
其糟糕的做法,你應該使用MVVM(你說我們可以評論;))。 – BradleyDotNET 2014-11-04 19:20:10