纯粹在后面的代码中创建自定义样式的WPF Checkbox

时间:2011-01-24 16:25:12

标签: c# wpf-controls styles

我正在尝试创建一个自定义CheckBox控件,理想情况下,它将由一个蓝色十字表示,当鼠标Mouse-Over事件发生时会变成较浅的蓝色,并在单击时触发Click事件。

我已经看到了使用控件模板和样式在XAML代码中执行此操作的方法,但不是纯粹在后面的代码中。我之前在代码中创建了自定义样式,并且应用得很好,但是我这次需要定制的数量有问题,例如用蓝色十字图像替换整个复选框。

有人知道这样做的标准方法吗?你能在XAML代码中创建一个完整的模板样式,然后在后面的代码中设置新复选框对象的属性时引用该模板吗?

提前致谢。

1 个答案:

答案 0 :(得分:2)

我讨厌这样做,因为它破坏了XAML的声明方法,但有时你需要这样做。

话虽如此,请查看FrameworkElementFactory类来构建您的XAML。这是一个非常整洁的模式。以下代码段显示了我在代码中为ListView创建DataTemplate的位置。我需要根据时间报告应用程序的一个月内的天数动态添加元素。

       GridView gv = new GridView();
        int i = 0;
        foreach (string s in vm.DateList)
        {
            string column = string.Format("DisplayTime[{0}].Hours", i);
            DataTemplate dt = new DataTemplate();

            DateTime date = DateTime.Parse(s);

            bool isWeekday = true;

            if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
            {
                isWeekday = false;
            }

            Binding binding = new Binding();
            binding.Path = new PropertyPath(column);
            binding.Mode = BindingMode.TwoWay;

            FrameworkElementFactory gridElement = new FrameworkElementFactory(typeof(Grid));
            gridElement.SetValue(Grid.WidthProperty, 60.0);
            gridElement.SetValue(Grid.HeightProperty, 94.0);
            gridElement.SetValue(Grid.MarginProperty, new Thickness(0.0, 0.0, 0.0, 4.0));

            if (!isWeekday)
            {
                gridElement.SetValue(Grid.BackgroundProperty, new SolidColorBrush(Color.FromRgb(65, 65, 65)));
            }


            FrameworkElementFactory txtelement = new FrameworkElementFactory(typeof(TextBox));
            txtelement.SetBinding(TextBox.TextProperty, binding);
            txtelement.SetValue(TextBox.WidthProperty, 40.0);
            txtelement.SetValue(TextBox.HeightProperty, 20.0);
            txtelement.SetValue(TextBox.VerticalAlignmentProperty, VerticalAlignment.Center);
            txtelement.SetValue(TextBox.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            txtelement.SetValue(TextBox.TextAlignmentProperty, TextAlignment.Right);

            gridElement.AppendChild(txtelement);

            dt.VisualTree = gridElement;

            gv.Columns.Add(new GridViewColumn()
            {
                Header = s,
                //                            DisplayMemberBinding = new Binding(column),
                CellTemplate = dt
            });
            i++;
        }

        ETCListView.View = gv;