我正在尝试以编程方式在运行时更改特定元素的颜色。该项目目前使用Telerik,我能够在运行时更改主题:这可以正常工作,没有任何问题。但是,我无法弄清楚如何在XAML中自定义形状元素的运行时更改填充或描边颜色。
在我的项目中,我有一个名为 _Icons.xaml 的ResourceDictionary
文件,其中包含矢量形状,可用作其他控件(如按钮)的内容。
我使用以下代码在运行时更改主题的标记颜色。
GreenPalette.Palette.MarkerColor = (Color)ColorConverter.ConvertFromString("#FF000000");
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyNamespace">
<ControlTemplate x:Key="Box">
<Viewbox>
<Rectangle Width="357" Height="357" Fill="#000000"/>
</Viewbox>
</ControlTemplate>
<ControlTemplate x:Key="BoxOutline">
<Viewbox>
<Rectangle Width="357" Height="357" StrokeThickness="45" Stroke="#000000"/>
</Viewbox>
</ControlTemplate>
</ResourceDictionary>
<telerik:RadButton>
<StackPanel>
<ContentControl Template="{StaticResource Box}" Height="58"/>
<TextBlock HorizontalAlignment="Center" Margin="0,5,0,0">Box</TextBlock>
</StackPanel>
</telerik:RadButton>
<telerik:RadButton>
<StackPanel>
<ContentControl Template="{StaticResource BoxOutline}" Height="58"/>
<TextBlock HorizontalAlignment="Center" Margin="0,5,0,0">BoxOutline</TextBlock>
</StackPanel>
</telerik:RadButton>
在 _Icons.xaml 中,我有以下几行:
<Rectangle Width="357" Height="357" Fill="#000000"/>
<Rectangle Width="357" Height="357" StrokeThickness="45" Stroke="#000000"/>
给出 App.xaml.cs 中的以下行:
GreenPalette.Palette.MarkerColor = (Color)ColorConverter.ConvertFromString("#FF000000");
我怎么能......
Fill
和/或 Stroke
的值(仅Fill
设置的元素只应更改Fill
值而不是从 App.xaml.cs 文件中添加Stroke
属性? 或...... Fill
或Stroke
以接收我的 App.xaml.cs 文件提供的值?感谢您抽出宝贵时间阅读我的问题。非常感谢任何有关此问题的帮助。
答案 0 :(得分:0)
首先,我建议您从资源表中弹出控件,以便您可以正确控制它们。
当你这样做时,去你的控件后面的代码,只使用背景使用的'SolidColorBrush'类型的'Color'的依赖属性,然后按元素名称绑定它,你必须至少构建项目一次在尝试绑定之前。
以下是编写依赖项属性的方法
提示:在VS写'propdp'并点击两次选项卡以显示模板,但你现在可以使用我的。
public Color _color
{
get { return (Color)GetValue(ColorProperty); }
set { SetValue(ColorProperty, value); }
}
public static readonly DependencyProperty ColorProperty =
DependencyProperty.Register("_color", typeof(Color), typeof(Fileentity), null);
构建完成后,转到xalm并将其放入矩形中:
<Grid.Background>
<SolidColorBrush Color="{Binding
_color,ElementName=YourControlName" />
</Grid.Background>
如果你做得对,你可以在你的页面上插入控件时访问这个属性,如
<local:YourcontrolName _color="{x:Bind MyColorProperty }"/>
其中'MyColorProperty'是实现INotifyPropertyChanged的属性。
另一种方法是直接在usercontrol上使用datacontext,并将颜色绑定到其中一个属性,如:
public YourControl(){
this.InitializeComponent();
this.DataContext = new MyClassDataContext();
var myContext= (MyClassDataContext)this.DataContext;
_color=MyContext.MyColorProperty;}
其中MyClassDataContext是包含您选择的Color属性(MyColorProperty)的任何给定类。
你需要一个Dependency属性,它与你之前显示的控件xalm绑定。
我知道这一切可能很难立刻掌握,因为它需要MvvM的基本知识。