有没有办法绑定到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;
}
答案 0 :(得分:1)
您可以在C#中执行此操作 - 您必须手动构建Binding:
// 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);
有关详细信息,请参阅How To: Create a Binding in Code。
答案 1 :(得分:1)
嗨尝试这样的事情
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>
我希望这会有所帮助。