我有自定义依赖属性的用户控件...
public static readonly DependencyProperty ImageKeyProperty =
DependencyProperty.Register("ImageKey", typeof(string), typeof(ImageSelector),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnImageKeyPropertyChanged));
public string ImageKey
{
get { return (string)GetValue(ImageKeyProperty); }
set { SetValue(ImageKeyProperty, value); }
}
private static void OnImageKeyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ImageSelector imageSelector = d as ImageSelector;
if (imageSelector == null) return;
if (e.NewValue == null || e.NewValue.ToString() == "")
{
imageSelector.Image.Source = null;
imageSelector.buttonSelect.Content = "select...";
imageSelector.Image.Visibility = Visibility.Collapsed;
}
else
{
imageSelector.Image.Source = ImageLibrary.GetImage(e.NewValue.ToString());
imageSelector.buttonSelect.Content = "change...";
imageSelector.Image.Visibility = Visibility.Visible;
}
imageSelector.PropertyChanged?.Invoke(imageSelector, new PropertyChangedEventArgs("ImageKey"));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ImageSelectWindow w = new ImageSelectWindow();
w.ShowDialog();
if (w.DialogResult.HasValue && w.DialogResult.Value)
{
this.ImageKey = w.SelectedImageKey;
}
}
如果我将ViewModel(即DataContext)绑定到它......
<myControl ImageKey={Binding Image} />
我是否应该能够以编程方式在自定义UserControl中设置ImageKey值并使绑定的ViewModel属性更新?显然不是,因为它不起作用。
我错过了什么? !?!?
答案 0 :(得分:0)
“我不能以编程方式设置ImageKey值吗?”
简短的回答:嗯...不。 抱歉,这已经很久了,但是以防万一有人发现它并感到奇怪。
您在这里绑定:
<myControl ImageKey={Binding Image} />
在这里,您正在破坏绑定:
this.ImageKey = w.SelectedImageKey;
总之,不,您不能以编程方式更新绑定属性。而是更新其绑定值:
(this.DataContext as MyViewModel).Image = w.SelectedImageKey;
玩得开心。