嗯,我正在做一个小项目,我发现没有必要实现一个完整的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