【发布时间】:2014-12-31 19:09:49
【问题描述】:
嗯,我正在做一个小项目,我发现没有必要实现完整的 MVVM。
我正在尝试在后面的代码中绑定一些属性,但无法使其工作。
重点是在后面的代码中使用 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,欢迎使用我们的 cmets。
.还...与Command 属性相关。在这种我不想使用 MVVM 方法的情况下,注册事件会更好吗?我发现使用自定义命令绑定有点乏味。
【问题讨论】:
-
这是不好的做法,你应该使用 MVVM(你说我们可以评论;))。
标签: c# wpf xaml binding dependency-properties