绑定到代码中的DependencyProperty(除了更改通知)
本文关键字:通知 代码 DependencyProperty 绑定 | 更新日期: 2023-09-27 17:57:40
有没有一种方法可以绑定到C#中的依赖属性(就像XAML一样)?
我知道我可以进行更改通知,但我希望有一种方法可以进行"双向"绑定。(因此,更改我的值会更改依赖属性。)
示例:
在我的用户控制视图中
public static readonly DependencyProperty IsRequiredProperty =
DependencyProperty.Register("IsRequired", typeof(bool),
typeof(MyUserControl), new FrameworkPropertyMetadata(default(bool)));
public bool IsRequired
{
get { return (bool)GetValue(IsRequiredProperty); }
set { SetValue(IsRequiredProperty, value); }
}
在我看来模型:
// This is the one I want bound to the dependency property.
bool IsRequired { //INotifyPropertyChanged getter and setter}
public void SomeCommandExec(Object obj)
{
// Update the dependency property by doing this:
IsEnabled = False;
}
您可以在C#中做到这一点-您必须手动构建绑定:
// You need these instances
var yourViewModel = GetTheViewModel();
var yourView = GetYourView();
Binding binding = new Binding("IsRequired");
binding.Source = yourViewModel;
binding.Mode = BindingMode.TwoWay;
yourView.SetBinding(YourViewType.IsRequiredProperty, binding);
有关详细信息,请参阅如何:在代码中创建绑定。
嗨,试试这个
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
Binding binding = new Binding("IsRequired")
{
Source = UserControl1.IsRequiredProperty,
Mode = BindingMode.TwoWay
};
}
}
public class ViewModel : INotifyPropertyChanged
{
private bool isRequired;
public bool IsRequired
{
get { return isRequired; }
set { isRequired = value; Notify("IsRequired"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
private CommandHandler mycommand;
public CommandHandler MyCommand { get { return mycommand ?? (mycommand = new CommandHandler((obj) => OnAction(obj))); } }
private void OnAction(object obj)
{
IsRequired = true;
}
}
public class CommandHandler : ICommand
{
public CommandHandler(Action<object> action)
{
action1 = action;
}
Action<object> action1;
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
action1(parameter);
}
}
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static readonly DependencyProperty IsRequiredProperty = DependencyProperty.Register("IsRequired", typeof(bool), typeof(UserControl1), new FrameworkPropertyMetadata(default(bool)));
public bool IsRequired
{
get { return (bool)GetValue(IsRequiredProperty); }
set { SetValue(IsRequiredProperty, value); }
}
}
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<local:UserControl1></local:UserControl1>
<Button Command="{Binding MyCommand}" Grid.Row="1" Content="Action"/>
</Grid>
我希望这会有所帮助。