【发布时间】:2020-03-23 12:46:11
【问题描述】:
通常我会在视图中创建所有对象并将其属性绑定到视图模型/模型。但是如果控件具有其他类型的属性,而不是字符串/布尔值呢?
例如一个简单的图表,它可以有“Chart.Legend”类型的图例
观点:
<ChartControl x:Name="{Binding ChartModelObject.Name}" Data="{Binding ChartModelObject.Data}">
<ChartControl.Legend Postiton="{Binding ChartModelObject.Legend.Position}">
<ChartControlLegend/>
</ChartControl.Legend">
</ChartControl>
使用 ViewModel
public class ChartViewModel
{
public ChartModel ChartModelObject{ get; set; }
}
和模型
public class ChartModel
{
public LegendModel Legend { get; set; }
public String Name { get; set; }
public IData Data { get; set; }
}
public class LegendModel
{
public PositionEnum Position { get; set; }
}
根据我的 ChartModels 属性“Legend”是否具有 LegendModel 类型的实例并且不为空,我想显示图例,否则不显示。现在我必须在视图中创建一个“ChartControl.Legend”类型的对象,或者以另一种方式将 ChartControl.Legend 直接绑定到 ChartModel.LegendModel。但是我该如何实现呢?
编辑:
一个更一般的例子
视图
<Button Content="{Binding Name}" FontSize="14" FontWeight="Bold">
<!-- Only use a LinearGradientBrush if there is a ExampleModelObject Object-->
<Button.Background>
<LinearGradientBrush StartPoint="0,0.5"
EndPoint="1,0.5">
<GradientStop Color="Green" Offset="{Binding ExampleModelObject.FirstPoint}" />
<GradientStop Color="White" Offset="{Binding ExampleModelObject.SecondPoint}" />
</LinearGradientBrush>
</Button.Background>
</Button>
ViewModel
public class ExampleViewModel
{
public ButtonBackgroundExampleModel ExampleModelObject{ get; set; }
public string Name {get;set}
}
模型
public class ButtonBackgroundExampleModel
{
public double FirstPoint { get; set; }
public double SecondPoint { get; set; }
}
根据 ViewModel 是否有 ButtonBackgroundExampleModel 的实例,我想创建一个 Button.Background.LinearGradientBrush。如果没有 ButtonBackgroundExampleModel(没有 FirstPoint、SecondPoint),则应该没有 Button.Background。所以,应该是:
<Button Content="{Binding Name}" FontSize="14" FontWeight="Bold">
</Button>
【问题讨论】:
-
"如果我的 ChartModels 属性 "Legend" 有一个 LegendModel 类型的实例并且不为空,我想显示图例,否则不" - 听起来像 DataTrigger
-
@Alexander:您应该在视图模型中创建
ChartModel。如果没有图例,视图中的(默认)模板应该注意不显示图例。 -
@mm8 但我如何注意未创建或显示 ChartControl.Legend(在视图中)?我必须在后面的代码中制作它还是如何在 xaml 中处理它?
-
@Alexander:请通过发布minimal reproducible example 说明您正在使用什么
ChartControl、您想要做什么以及您尝试过什么。 -
@mm8 添加了一个更通用的示例