【问题标题】:Bind color from绑定颜色来自
【发布时间】:2018-01-11 16:15:12
【问题描述】:

我的 DataGrid 包含具有 3 个数值参数和颜色的图形对象列表(抛物线)(属性名为 br,类型为 SolidColorBrush)。

我想从放置在DataGridTemplateColumn 中的ComboBox 中选择颜色,以便将类型(SolidColorBrush) 的选定值保存在DataGrid 中选定项的br 属性中。

图片显示主窗口是如何工作的:

创建新项目时,它会自动添加到 DataGrid,但 DataGrid 中的Color 列不显示其颜色。在代码中以编程方式设置 br 值时,ComboBox 也不会更新。

当我从下拉列表中手动选择颜色值时,它不会保存在所选项目的br 属性中。

在这种情况下如何正确组织数据绑定?

我的简单图形元素类:

using System;
using System.Windows.Media;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfParabola
{
    public class Parabola
    {
        public double a { get; set; } = 1;
        public double b { get; set; } = 1;
        public double c { get; set; } = 1;
        public SolidColorBrush br { get; set; } = new SolidColorBrush(Colors.Black);
        PropertyInfo[] brushes = typeof(Brushes).GetProperties();

        public Parabola() { }
        public Parabola(Random rnd)
        {
            a = (double)rnd.Next(2, 20) / 100;
            b = (double)rnd.Next(2, 20) / 100;
            c = (double)rnd.Next(1, 30);
            int random = rnd.Next(brushes.Length);
            br = (SolidColorBrush)brushes[random].GetValue(null, null);
        }
        public Parabola(double _a, double _b, double _c)
        {
            a = _a;
            b = _b;
            c = _c;
        }
        public double y(double x)
        {
            return Math.Pow(a * x, 2) + b * x + c;
        }
    }
}

主窗口代码:

<Window x:Class="WpfParabola.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfParabola"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="725"
    x:Name="_this">
<Window.Resources>
    <ResourceDictionary>
        <ObjectDataProvider MethodName="GetType"
ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
            <ObjectDataProvider.MethodParameters>
                <sys:String>System.Windows.Media.Colors, PresentationCore,
        Version=3.0.0.0, Culture=neutral,
        PublicKeyToken=31bf3856ad364e35</sys:String>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"
MethodName="GetProperties" x:Key="colorPropertiesOdp">
        </ObjectDataProvider>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="300"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <DataGrid Grid.Row="0"
              Grid.Column="0"
              Name="parabolasDataGrid"
              CanUserAddRows="False"
              ItemsSource="{Binding parabolas}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="a" Width="20" Binding="{Binding a}"></DataGridTextColumn>
            <DataGridTextColumn Header="b" Width="20" Binding="{Binding b}"></DataGridTextColumn>
            <DataGridTextColumn Header="c" Width="20" Binding="{Binding c}"></DataGridTextColumn>
            <DataGridTemplateColumn Header="Color" Width="150">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}"
                                  SelectedItem ="{Binding br}">
                            <ComboBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Width="50" Height="{Binding ElementName=FontSize+4}" Margin="2" Background="{Binding Name}"/>
                                        <TextBlock  TextAlignment="Left" VerticalAlignment="Center" Text="{Binding Name}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ComboBox.ItemTemplate>
                        </ComboBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Canvas Grid.Row="0" Grid.Column="1" Name="parabolaCanvas"></Canvas>
    <StackPanel Grid.Row="1" Grid.Column="1">
        <Button Padding="3" Margin="3" Click="Button_Click">Add parabola</Button>
        <Button Padding="3" Margin="3" IsCancel="True" Click="Button_Click_1">Close</Button>
    </StackPanel>
</Grid>

及其背后的代码:

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace WpfParabola
{
    public partial class MainWindow : Window
    {
        Random rnd = new Random();
        public ObservableCollection<Parabola> parabolas { get; set; } = new ObservableCollection<Parabola>();
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            parabolasDataGrid.AutoGenerateColumns = false;
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Path path = new Path();
            PathGeometry geometry = new PathGeometry();
            PathFigure figure = new PathFigure();
            Parabola p = new Parabola(rnd);
            parabolas.Add(p);
            figure.StartPoint = new Point(1, p.y(1));
            for(double x=2; x<300; x += 0.5)
            {
                figure.Segments.Add(new LineSegment()
                {
                    Point = new Point(x, p.y(x))
                });
            }
            path.Stroke = p.br;
            path.StrokeThickness = 2;
            geometry.Figures.Add(figure);
            path.Data = geometry;
            parabolaCanvas.Children.Add(path);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}

【问题讨论】:

    标签: c# wpf combobox datagrid datagridtemplatecolumn


    【解决方案1】:

    因此,您有一个抛物线集合,您将集合绑定到该集合,但您没有将 ComboBox 上的 SelectedItem 绑定到变量 BR。您还需要使用 NotifyPropertyChanged,以便在选择不同颜色时更新网格。

    【讨论】:

    • 我加了SelectedItem ="{Binding br}",对吗?但是我的Parabola 类中的属性br 无论如何都没有更新。也许问题在于类型转换。 ComboBox 填充了StaticResource colorPropertiesOdp,这是PropertyInfo 集合,而不是画笔集合。如何处理?
    • 这将是一个问题,您可以使您选择的项目成为任何类型的 colorPropertiesOdp 并且当属性更改时,更新您的 br 属性。但是,我会创建一个具有您需要的属性的实际 Type,而不是 propertyInfo 集合,并将 comobBox 绑定到该集合。
    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多