仅使用C#更改图片

时间:2011-08-20 10:48:06

标签: c# wpf

目标:
如果文本框txtSearch中有任何输入数据,请将图片从picEnlarger更改为picXmark。

如果文本框中没有数据输入,则应显示图片picEnlarger,并隐藏picXmark。

问题:
我知道如何在xaml中完成它而不是在c#代码中。

我想通过仅使用C#将图片从/更改为可见性或隐藏。

请记住,我想使用更少的xaml代码。

我还尝试使用以下代码在文本框txtSearch的事件方法(private void txtSearch_TextChanged(object sender,TextChangedEventArgs e))中隐藏/显示图片:

picXmark.Visibility = Visibility.Visible;
picEnlarger.Visibility = Visibility.Hidden;

不幸的是,我检索此消息“对象引用未设置为对象的实例”。

<TextBox Name="txtSearch" Width="143.243" TextChanged="txtSearch_TextChanged" Text="Search article" PreviewMouseLeftButtonDown="txtSearch_PreviewMouseLeftButtonDown" />
    <Image x:Name="picEnlarger" Height="14" Width="14" Source="/MediaStore;component/Bilder/search_enlarger2.gif" />
    <Image x:Name="picXmark" Height="8" Width="8" Source="/MediaStore;component/Bilder/search_xmark.gif" />
</TextBox>

2 个答案:

答案 0 :(得分:0)

TextChanged事件可以正常工作,问题是它在所有控件初始化之前被引发。

尝试这样的事情

private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
{
    if (picEnlarger != null && picXmark != null)
    {
        if (txtSearch.Text == "")
        {
            picXmark.Visibility = Visibility.Visible;
            picEnlarger.Visibility = Visibility.Hidden; 
        }
        else
        {
            picXmark.Visibility = Visibility.Hidden;
            picEnlarger.Visibility = Visibility.Visible; 
        }
    }
}

答案 1 :(得分:0)

Images放在Textbox之前

<Image x:Name="picEnlarger" Height="14" Width="14" Source="/MediaStore;component/Bilder/search_enlarger2.gif" />
<Image x:Name="picXmark" Height="8" Width="8" Source="/MediaStore;component/Bilder/search_xmark.gif" />
<TextBox Name="txtSearch" Width="143.243" TextChanged="txtSearch_TextChanged" Text="Search article" PreviewMouseLeftButtonDown="txtSearch_PreviewMouseLeftButtonDown" />