从类中更改MainWindow中的图像

时间:2014-03-17 11:33:57

标签: c# wpf

我试图在我的MainWindow中更改显示图片的位置,所以在其中我有:

<Grid Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="58" Margin="2,0,0,0" Grid.Row="1" VerticalAlignment="Top" Width="100">
    <Image Name="BartenderX1X1Image" Source="/Images/KelnerZTaca.gif" HorizontalAlignment="Left" Height="58" VerticalAlignment="Stretch" Width="100"/>
    <Image Name="BartenderX1X2Image" HorizontalAlignment="Left" Height="58" VerticalAlignment="Stretch" Width="100"/>
</Grid>

我用方法创建了类控件:

public void BartenderMooveRight()
{
    foreach (Window window in Application.Current.Windows)
    {
        if (window.GetType() == typeof(MainWindow))
        {
            (window as MainWindow).BartenderX1X1Image.Source = null;
            (window as MainWindow).BartenderX1X2Image.Source = bartenderImage.Source;
        }
    }
}

当我从我的MainWindow打电话时,没有任何事情发生。为什么来自BartenderX1X1Image的图片不会消失而BartenderX1X2Image.Source中的图片不会显示?

2 个答案:

答案 0 :(得分:2)

你在哪个面板上放置了两个图像,如果它在面板内部,则它们相互叠加。尝试使用StackPanel。 像这样,

<StackPanel Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="58"
            Margin="2,0,0,0" Grid.Row="1" VerticalAlignment="Top" Width="100">
   <Image Name="BartenderX1X1Image" Source="/Images/KelnerZTaca.gif" 
          HorizontalAlignment="Left" Height="58" VerticalAlignment="Stretch"
          Width="100"/>
   <Image Name="BartenderX1X2Image" HorizontalAlignment="Left" Height="58" 
          VerticalAlignment="Stretch" Width="100"/>
</StackPanel>

答案 1 :(得分:0)

尝试为Bartender X1X1Image设置Visibility.Collapsed的可见性,为Bartender X1X2Image设置Visibility.Visible。