我需要动态加载图表(包括自定义 UserControl 的 XAML,ScrewControl
)。
我正在研究从 ViewModel 类绑定依赖属性 ( Status
) 的方法。ScrewControl
挑战在于一个图表可以包含不同数量的ScrewControl
s,每个 s 都需要绑定到字典或集合中的数据ViewModel
。
我已经解决了使用 ViewModel 动态加载 XAMLXamlReader
但不确定如何将ScrewControl
s 与 Collection/dictionary 绑定的第一个挑战。
查看模型类
public class AssemblyViewModel
{
public Dictionary<int, ScrewStatus> Screws { get; set; }
public FrameworkElement Image { get; set; }
...
}
查看课程
public partial class AssemblyView : UserControl
{
private AssemblyViewModel viewModel;
public AssemblyView(AssemblyViewModel viewModel)
{
InitializeComponent();
DataContext = this.viewModel = viewModel;
Loaded += OnLoaded;
}
public FrameworkElement XamlContent
{
get { return (FrameworkElement)GetValue(XamlContentProperty); }
set { SetValue(XamlContentProperty, value); }
}
// Using a DependencyProperty as the backing store for Content. This enables animation, styling, binding, etc...
public static readonly DependencyProperty XamlContentProperty =
DependencyProperty.Register("XamlContent", typeof(FrameworkElement), typeof(AssemblyView), new PropertyMetadata(null, OnXamlChanged));
private static void OnXamlChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
var view = dependencyObject as AssemblyView;
var element = args.NewValue as FrameworkElement;
if (null != element)
{
view.ContentControl.Children.RemoveRange(0, 1);
view.ContentControl.Children.Add(element);
var screws = element.FindChildren<Screw>();
try
{
foreach (var screw in screws)
{
// The ScrewControl has a name properties like "Screw_1", 1 is used as the key of the dictionary and Status as the Value
var parts = screw.Name.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
if (2 == parts.Length)
{
BindingOperations.SetBinding(
screw,
Screw.ScrewStatusProperty,
new Binding(/*not sure what goes here*/)
{
Source = view.viewModel.Screws,
});
}
}
}
catch (Exception e)
{
throw;
}
}
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
// This works and loads the diagram
BindingOperations.SetBinding(
this,
XamlContentProperty,
new Binding("Image")
{
Source = this.viewModel
});
}