我在用户控件中有一个网格:
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneAccentBrush}">
<Image
x:Name="imgBack"
Opacity=".25" />
<Grid VerticalAlignment="Top" HorizontalAlignment="Left">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- Some textblocks -->
</Grid>
图像的网格和源的大小在运行时动态设置:
public void ChangeSizeAndImage(int width, int height, string backImagePath)
{
// Set the height and width
LayoutRoot.Width = width;
LayoutRoot.Height = height;
// Set the background image
imgBack.Source = new BitmapImage(new Uri(backImagePath, UriKind.RelativeOrAbsolute));
this.UpdateLayout();
}
然后我调用一个从 ui 元素生成 jpeg 并将其保存到 IsolatedStorage 的方法(稍后添加到 Windows Phone Live Tile)
public static Uri CreateImageFromUIElement(UIElement element, int width, int height)
{
// Instance to store the image in
IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication();
// Random ID to use for the file name
string id = Guid.NewGuid().ToString("n");
// create directory to read/write from
const string shellContentDirectory = "Shared\\ShellContent";
userStore.CreateDirectory(shellContentDirectory);
// Render the UIElement into a writeable bitmap
WriteableBitmap bitmap = new WriteableBitmap(element, new CompositeTransform());
// Save the bitmap to a file. This stream must be closed in order to be read later
string imagePath = shellContentDirectory + "\\" + id + ".jpg";
using (IsolatedStorageFileStream stream = userStore.OpenFile(imagePath, System.IO.FileMode.Create))
{
bitmap.SaveJpeg(stream, width, height, 0, 100);
}
// Uri to get us to the image
Uri imageUri = new Uri("isostore:/" + imagePath.Replace('\\', '/'));
return imageUri;
}
我能够成功地使用磁贴上的图像,除了我只看到黑色背景的图像,我看不到任何文字。我认为这与 jpeg 和透明 PNG 有关,但是,我在上面的网格上设置了一种颜色的背景,所以我不确定为什么它会被认为是透明的。
编辑 1
我正在以编程方式初始化此用户控件,设置一些属性,并将其传递给 create image 方法。我发现如果我将此用户控件添加到页面,然后使用调用创建图像方法,它工作得很好。一定有一些关于它在页面上呈现的东西,导致所有东西都正确排列。不幸的是,这种方法在我的情况下是不可能的。有什么步骤可以让这个工作吗?UpdateLayout();
在控件上不起作用。