通过C#动态创建窗口我试图为它分配一个渐变背景,但我卡住了通过c#代码再现XAML
创建窗口(我试图删除尽可能多的无关代码)
static LinearGradientBrush backgroundLinearBrush = null;
static Window MsgBox(int parlnNum, string parflPath, string parMethodName, string Msgbx_Contnt)
{
var w_mbx = new Window(); w_mbx.Topmost = true;
w_mbx.Width = 1000; w_mbx.Height = 179;
//from an online example I tried adding the rectangle
// as the gradient owner- not sure if this is the way to go
Rectangle GradientRectangle = new Rectangle() { Width = w_mbx.Width, Height = w_mbx.Height };
if (backgroundLinearBrush == null)
{
GradientStopCollection gradientStopsLinearBrush = new GradientStopCollection();
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#EF63BADF"), 0.0));
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#E856B7C9"), 0.555));
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#C543C0DB"), 0.333));
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#E734ABDA"), 0.444));
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#927FE2E2"), 0.777));
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#E974CFC1"), 0.555));
gradientStopsLinearBrush.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#D076C5EB"), 0.275));
LinearGradientBrush backgroundLinearBrush = new LinearGradientBrush(gradientStopsLinearBrush)
{
StartPoint = new Point(0, 0.5),
EndPoint = new Point(1, 0.5)
};
GradientRectangle.Fill = backgroundLinearBrush;
}
然后构建窗口中的元素
Grid g = new Grid();
Grid.SetRow(GradientRectangle, 1);
Grid.SetColumn(GradientRectangle, 1);
StackPanel spM = new StackPanel();
TextBlock TblckErrMsg = new TextBlock();
TblckErrMsg.Name = "Tblck_ErrMsg";
TextBlock TblckLine = new TextBlock();
TblckLine.Name = "Tblck_Line";
TblckLine.Text = "[GoToError]";
TblckLine.MouseDown += new System.Windows.Input.MouseButtonEventHandler((s, e) => TblckLine_MouseDown(s, e, parflPath, parlnNum));
spM.Children.Add(TblckErrMsg);
spM.Children.Add(TblckLine);
g.Children.Add(spM);
w_mbx.Content = g;
return w_mbx;
}
我想这里有一些缺失的步骤,这是我无法达到要求的结果的原因。
答案 0 :(得分:0)
为什么不为它制作风格?基本上是:
myDynamicWindow.SetResourceReference(Window.Style, "NameOfDefinedStyle");
(相当于<Window Style="{DynamicResource NameOfDefinedStyle}"/>
)。如果您有多种样式的窗口,并且不想复制/粘贴模板,请定义一个包含所有应共享的属性的样式,并将单个新样式基于原始样式。这可以使用以下语法完成:
<Style x:Key="WindowBase" TargetType="{x:Type Window}">
<!-- Shared properties -->
</Style>
<Style x:Key="DynamicWindowStyle" BasedOn="{StaticResource WindowBase}">
<!-- You can set a unique background gradient here -->
</Style>
注意:更改窗口的背景并不像更改网格那么简单。如果您没有模板来覆盖Window控件的默认值,请告诉我,我将发布完整的工作示例。