【问题标题】:Change picture using C# ONLY仅使用 C# 更改图片
【发布时间】:2011-08-20 10:48:06
【问题描述】:

目标:
如果文本框 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>

【问题讨论】:

  • 我猜你正试图在这些对象被绘制到 WPF 窗口之前更改可见性......
  • 您的 XAML 对我没有任何意义 - 它甚至无效。
  • 使用更少的 XAML 通常意味着很多更多的代码隐藏,你为什么想要那个?
  • H.B. = 当我在我的应用程序中使用更多组件时,能够更灵活地使用源代码。

标签: c# wpf


【解决方案1】:

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; 
        }
    }
}

【讨论】:

    【解决方案2】:

    像这样将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" />
    

    【讨论】:

    • 不是一个非常强大的解决方案。如果你想在 xaml 中移动一些控件,程序可能会再次崩溃
    • 图片需要在文本框内。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多