【问题标题】:Bind control to another property将控件绑定到另一个属性
【发布时间】:2015-07-28 12:07:11
【问题描述】:

我的老板下载了一个我必须在应用程序中使用的 xaml 控件。看起来不错,但内部逻辑有个奇怪的问题—— 属性CurrentColor(我需要在我们的应用程序中使用)在control.xaml.cs 文件中定义,例如:

public SolidColorBrush CurrentColor
{
     get { return (SolidColorBrush)GetValue(CurrentColorProperty); }
     set
     {
          SetValue(CurrentColorProperty, value);
          ActiveColor = CurrentColor;
     }
}

我在我的对话框中使用这个控件(它有自己的视图模型类)和 我正在写这种绑定:

CurrentColor="{Binding myOwnViewModel.ColorActualValue, Mode=Default, UpdateSourceTrigger=PropertyChanged}">

myOwnViewModel.cs(实现INotifyPropertyChanged)我有我的财产

public SolidColorBrush ColorActualValue{ // here is some logic}

但是当我调试一个应用程序时,我从来没有针对我的 CurrentColor - 我总是从control.xaml.cs 转到CurrentColor

如何将这个“第三方”控件从我的ViewModel 绑定到我的属性?

也许这是因为 (control.xaml.cs):

  public static DependencyProperty CurrentColorProperty =
            DependencyProperty.Register("CurrentColor", typeof(SolidColorBrush), typeof(ColorPickerComboBox), new PropertyMetadata(Brushes.Chocolate));
        public static RoutedEvent ActiveColorChangedEvent = EventManager.RegisterRoutedEvent("ActiveColorChanged",
            RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ColorPickerComboBox)); 

我找到了问题 What's wrong with "DataContext = this" in WPF user controls? 并从该控件的构造函数中删除了 DataContext = this; - 但这仍然没有帮助

【问题讨论】:

  • 将数据上下文设置为您的视图模型,然后从您的绑定声明中删除视图模型
  • 您绑定到属性 myOwnViewModel.ColorActualValue 但在您的 ViewModel 中它命名为 CurrentColor。检查输出窗口是否存在绑定错误。
  • GreenEyedAndy - 抱歉这个错误我已经更正了问题
  • 您能否提供一些指向控制项目/站点/完整代码的链接?
  • 你的 ColorPickerComboBox set, and what is it? The binding of myOwnViewModel.ColorActualValue 的 DataContext 怎么样?看起来很奇怪,因为这意味着你绑定到 ColorPickerComboBox.DataContext.myOwnViewModel.ColorActualValue,我怀疑 myOwnViewModel 要么是错误,要么是不公开的。您很可能正在尝试绑定到 ColorPickerComboBox.DataContext.ColorActualValue,其中 DataContext 为 myOwnViewModel。如果是这种情况,您的绑定应该只是 {Binding ColorActualValue}

标签: c# wpf xaml


【解决方案1】:

绑定应该是这样的吗?

CurrentColor="{Binding ColorActualValue, Mode=Default, UpdateSourceTrigger=PropertyChanged}">

“对话框”的 DataContext 必须是包含 ColorActualValue 属性的 ViewModel 类

public Dialog()
{
    DataContext = new myOwnViewModel();
}

【讨论】:

  • 不,我试过这个。无论如何,谢谢你的回答,看看我更新的问题
  • 我无法将 myOwnViewModel 的实例传递给 Dialog 构造函数 - 首先 Dialog 在另一个项目中,其次 myOwnViewModel 不是静态类,并且具有 Dialog 所在项目中不存在的参数。我将尝试在可以使用 myOwnViewModel 的地方在 InitializeComponent 之后编写适当的代码(将控件更改为具有适当 DataContext 的另一个控件),但我认为这是一种不好的做法
  • 是的,听起来不太好。看看一些示例应用程序是如何组合在一起的
猜你喜欢
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 2013-04-20
  • 2010-11-14
  • 1970-01-01
  • 2012-03-27
相关资源
最近更新 更多