如何以编程方式将图像放入进度条(WPF)

时间:2015-11-26 16:45:17

标签: c# wpf xaml programmatically-created

我是WPF的新手,我需要一些帮助将图像放入进度条(以编程方式)。

我发现了这个(并且有效):

<ProgressBar.Template>
    <ControlTemplate>
        <Grid>
            <Image Name="PART_Track" Source="MyImage" Stretch="Fill"/>
            <Rectangle Name="PART_Indicator" Fill="BlanchedAlmond" HorizontalAlignment="Left"/>
        </Grid>
    </ControlTemplate>
</ProgressBar.Template>

我只需要帮助将XAML代码转换为C#代码。

1 个答案:

答案 0 :(得分:0)

这将帮助您入门:

FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));

FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));
image.Name = "PART_Track";
ImageSource source = new BitmapImage(...); // create it
image.SetValue(Image.SourceProperty, source);
image.SetValue(Image.StretchProperty, Stretch.Fill);

grid.AppendChild(image);

FrameworkElementFactory rectangle = new FrameworkElementFactory(typeof(Rectangle));
rectangle.Name = "PART_Indicator";
rectangle.SetValue(Rectangle.FillProperty, new SolidColorBrush(Colors.BlanchedAlmond));
rectangle.SetValue(Rectangle.HorizontalAlignmentProperty, HorizontalAlignment.Left);

grid.AppendChild(rectangle);

    ControlTemplate ct = new ControlTemplate(typeof(ProgressBar));
ct.VisualTree = grid;

MyProgressBar1.Template = ct;