【发布时间】:2022-01-16 00:29:30
【问题描述】:
我正在尝试在我的资源字典中创建一个标准 UI 元素(内容控件),这样我只需通过属性将数据发送给它,就可以轻松地在我的用户控件上创建多个圆形图。
我现在想将
绘制图形的 Xaml 代码(让我们说 Window.xaml 以供进一步参考):
<ContentControl x:Name="CircGraphCrypto" Style="{StaticResource circularGraphStocks}" local:IconProperties.CircGraphSeriesBinding="SeriesCollection"/>
本地是我将传递 Xaml 后端代码中的 SeriesCollection 名称的地方。在这种情况下,名称是 SeriesCollection。
资源字典代码:
xmlns:local="clr-namespace:AutomationProject"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
<!-- Circular graph stocks -->
<Style x:Key="circularGraphStocks" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Border Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Grid.RowSpan="2" Style="{StaticResource borderRounded}">
<Grid Margin="5,10,5,5">
<lvc:PieChart Series="{Binding Path=(local:IconProperties.CircGraphSeriesBinding), Mode=TwoWay, RelativeSource={RelativeSource Self}}"
LegendLocation="Right" InnerRadius="10" Margin="5,5,5,5" Foreground="White">
<lvc:PieChart.ChartLegend>
<lvc:DefaultLegend BulletSize="20"></lvc:DefaultLegend>
</lvc:PieChart.ChartLegend>
<lvc:PieChart.DataTooltip>
<lvc:DefaultTooltip BulletSize="20" Foreground="Black"></lvc:DefaultTooltip>
</lvc:PieChart.DataTooltip>
</lvc:PieChart>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后我尝试向 附楼盘代码: namespace AutomationProject
{
public class IconProperties : DependencyObject
{
public static DependencyProperty CircGraphSeriesBindingProperty =
DependencyProperty.RegisterAttached("CircGraphSeriesBinding", typeof(string), typeof(IconProperties),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits));
public static string GetCircGraphSeriesBinding(DependencyObject obj)
{
string dataBinding = "{Binding " + (string)obj.GetValue(CircGraphSeriesBindingProperty) + "}";
MessageBox.Show(dataBinding);
return dataBinding;
}
public static void SetCircGraphSeriesBinding(DependencyObject obj, string value)
{
obj.SetValue(CircGraphSeriesBindingProperty, value);
}
}
}
【问题讨论】:
-
请注意,您不需要从 DependencyObject 派生来声明附加属性。最好声明
public static class IconProperties { ... } -
除此之外,从附加属性的 getter 返回除
(string)obj.GetValue(CircGraphSeriesBindingProperty)以外的任何内容都是错误的。 Binding 表达式字符串根本没有意义,因为这样的表达式必须由 XAML 解析器解析才能转换为实际的 Binding。 -
嗯,我对这一切都很陌生,发现绑定很难完全理解。我看到的所有不同的解决方案只会让我感觉更糟:)。感谢您的信息。明天我将尝试实施。你也知道我应该在谷歌上看什么方向来解决我的问题吗?我应该返回一个绑定而不是一个说绑定的字符串吗?
-
@JorisBeuls 您似乎误解了 Xaml 语法。您可以将其编写为 Xaml 中的文本,但不能将其视为字符串值。如果您仍想使用附加属性,则类型应为
SeriesCollection而不是字符串。如何连接属性和实际数据取决于您的项目。
标签: c# wpf data-binding