Tam*_*hen 11 c# wpf xaml bitmapsource resourcedictionary
我想在WPF中创建一个On/Off按钮,我想让它在用户点击它时改变它的外观(如果它是关闭,如果它关掉,则切换到打开)使用图像.我将要使用的图像添加到资源中:
<Window.Resources>
<Image x:Key="Off1" Source="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" />
<Image x:Key="On1" Source="/WPFApplication;component/Images/on_button.png" Height="30" Width="70"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
而事件代码是,"flag"是一个布尔局部变量,初始化为true:
private void OnOff1Btn_Click(object sender, RoutedEventArgs e)
{
if (flag)
{
OnOff1Btn.Content = FindResource("Off1");
flag = false;
}
else
{
OnOff1Btn.Content = FindResource("On1");
flag = true;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我需要创建2个开/关按钮,它们的行为相同.当我尝试为第二个按钮使用相同的资源时,我得到了一个例外:
Specified element is already the logical child of another element. Disconnect it first.
Run Code Online (Sandbox Code Playgroud)
我可以在第二个按钮中使用相同的图像资源,还是必须将图像作为具有不同密钥的资源再次添加?
Art*_*iom 15
将您的样式中的共享设置为false
<StackPanel >
<StackPanel.Resources>
<Image x:Key="flag" Source="flag-italy-icon.png" Width="10" x:Shared="false"/>
</StackPanel.Resources>
<ContentControl Content="{DynamicResource flag}" />
<ContentControl Content="{DynamicResource flag}" />
Run Code Online (Sandbox Code Playgroud)
Til*_*lak 12
您应该使用BitmapImage进行图像共享.
<BitmapImage x:Key="Off1" UriSource="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" />
<BitmapImage x:Key="On1" UriSource="/WPFApplication;component/Images/on_button.png" Height="30" Width="70"/>
Run Code Online (Sandbox Code Playgroud)
之后,您可以使用BitmapImage 创建多个图像
在XAML中
<Button ..>
<Button.Content>
<Image Source="{StaticResource Off1}" />
</Button.Content>
</Button>
Run Code Online (Sandbox Code Playgroud)
在代码中
Image image = new Image();
image.Source = FindResource("Off1");
OnOff1Btn.Content = image;
Run Code Online (Sandbox Code Playgroud)