我正在製作一個小型的UWP應用程序,其中每個頁面都具有相似的佈局。我在this thread之後創建了一個自定義UserControl,但我無法圍繞如何將圖像源傳遞到UserControl的背景圖像。UWP將圖像源傳遞給用戶控件作爲背景
如果我刪除對bgImage的引用,並且只刪除mainContent,那麼整個事情就會按預期工作。
如何將背景圖像源或URI傳遞給UserControl以用於控件?
用戶控件XAML:
<UserControl
x:Class="App1.MainTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid Background="Black">
<!-- Background image grid -->
<Grid Margin="0">
<Grid.Background>
<ImageBrush Opacity="100" ImageSource="{x:Bind bgImage}" Stretch="UniformToFill"/>
</Grid.Background>
<!-- Content grid -->
<Grid Margin="25" x:Name="contentGrid" Opacity="100">
<!-- Darkened insert -->
<Border BorderThickness="1" CornerRadius="8" BorderBrush="Black">
<Rectangle Name="Background" Opacity="0.55" Fill="Black" />
</Border>
<StackPanel VerticalAlignment="Center">
<!-- Content here. -->
<ContentPresenter Content="{x:Bind mainContent}" />
</StackPanel>
</Grid>
</Grid>
</Grid>
</UserControl>
MainTemplate.CS:
public sealed partial class MainTemplate : UserControl
{
public MainTemplate()
{
this.InitializeComponent();
}
public static readonly DependencyProperty bgImageProperty = DependencyProperty.Register("bgImage", typeof(ImageSource), typeof(MainTemplate), new PropertyMetadata(null));
public object bgImage
{
get { return GetValue(bgImageProperty); }
set { SetValue(bgImageProperty, value); }
}
public static readonly DependencyProperty mainContentProperty = DependencyProperty.Register("mainContent", typeof(object), typeof(MainTemplate), new PropertyMetadata(null));
public object mainContent
{
get { return GetValue(mainContentProperty); }
set { SetValue(mainContentProperty, value); }
}
}
最後,來自我嘗試使用(MainPage.xaml中)的頁面的一個例子:
<local:MainTemplate>
<local:MainTemplate.bgImage>
<Image Source="Assets/backgrounds/tailings 2.jpg"/>
</local:MainTemplate.bgImage>
<local:MainTemplate.mainContent>
<Button
x:Name="app1"
Content=""
HorizontalAlignment="Center"
Click="app1_Click"
Width="426"
Height="134"
Style="{StaticResource noMouseoverHover}"
>
<Button.Background>
<ImageBrush ImageSource="Assets/logos/image.png"/>
</Button.Background>
</Button>
</local:MainTemplate.mainContent>
</local:MainTemplate>
我在編譯/運行時遇到的錯誤是:
Error Invalid binding path 'bgImage' : Cannot bind type 'System.Object' to 'Windows.UI.Xaml.Media.ImageSource' without a converter App1
不是100%確定如何解決它,但是您正在使用類型安全的x:綁定對象類型屬性。可能只是「公開的ImageSource bgImage {...}」。 –