这是关于使用 MVVM 的最佳实践建议。
当元素被放入其中时,我需要填充一个包装面板。元素不统一,它们可以是标签或文本框。根据参数的值,添加的元素会有所不同。
我在后面的代码中做到了这一点。现在我正在将整个事情转移到一个 MVVM 模型中,我坚持这样做的方法而不影响 MVVM 核心原则。在这段代码中,我同时拥有紧密相关的 UI 元素和逻辑内容;而且我已经无法将两者分开以适应 MVVM。
我尝试在 VM 中创建 UI 元素,填充 UIElement 类型的 ObservableCollection 并将其绑定到 itemssource 属性(随后我将 wrappanel 更改为 listview 以便在整个过程中有效)。但这并没有奏效,因为当我绑定元素时,代码无法理解哪个 UIelement。
下面发布的是我需要分开的代码部分:
private void CreateVisulaQueryContent() {
VisualQueryObject visualQueryData = new VisualQueryObject();
VisualQueryObject helperVisualQueryObject = DraggedData as VisualQueryObject;
//***Taking a copy of the static DraggedData object to be bound
visualQueryData.ColumnDiscriptor = helperVisualQueryObject.ColumnDiscriptor;
visualQueryData.ComparedValue = helperVisualQueryObject.ComparedValue;
visualQueryData.JoinWithColumnDescriptor = helperVisualQueryObject.JoinWithColumnDescriptor;
visualQueryData.LabelType = helperVisualQueryObject.LabelType;
visualQueryData.OperatorValue = helperVisualQueryObject.OperatorValue;
if (visualQueryData.LabelType == "column")
{
ColumnDescriptionObject descriptionValue = visualQueryData.ColumnDiscriptor;
Label droppedElement = new Label();
Binding binding = new Binding();
binding.Source = visualQueryData;
binding.Path = new PropertyPath("ColumnDiscriptor");
binding.Mode = BindingMode.TwoWay;
droppedElement.SetBinding(Label.DataContextProperty, binding);
droppedElement.Content = visualQueryData.ColumnDiscriptor.TableName + "." + visualQueryData.ColumnDiscriptor.ColumnName;
droppedElement.Foreground = Brushes.White;
droppedElement.Background = Brushes.DarkOrange;
droppedElement.BorderThickness = new Thickness(5);
droppedLabel.MouseDoubleClick += columnLabel_MouseDown;
ViewUIElements.Add(droppedElement);
}
else if (visualQueryData.LabelType == "controller")
{
Label droppedElement = new Label();
Binding binding = new Binding();
binding.Source = visualQueryData;
binding.Path = new PropertyPath("OperatorValue");
binding.Mode = BindingMode.TwoWay;
droppedElement.SetBinding(Label.DataContextProperty, binding);
droppedElement.Content = draggedContent.OperatorValue;
droppedElement.Foreground = Brushes.White;
droppedElement.Background = Brushes.Crimson;
droppedElement.BorderThickness = new Thickness(5);
droppedElement.MouseDoubleClick += columnLabel_MouseDown;
ViewUIElements.Add(new Label());
}
else if (visualQueryData.LabelType == "value")
{
TextBox droppedElement = new TextBox();
Binding binding = new Binding();
binding.Source = visualQueryData;
binding.Path = new PropertyPath("ComparedValue");
binding.Mode = BindingMode.TwoWay;
droppedElement.SetBinding(TextBox.TextProperty, binding);
droppedElement.MouseDoubleClick += columnLabel_MouseDown;
ViewUIElements.Add(droppedElement);
}
QueryDesignerModel.QueryDesignHelperCollection.Add(visualQueryData);
}
任何帮助都深表感谢!