如何在Windows Phone 7 XAML中编写检查TextBlock是否包含特定字符串的代码?

4
我有一个文本块和一个文本框,我需要检查文本块是否包含文本框的值,如果是,则应该用一些颜色突出显示特定的值. . .
例如,
TextBlock.Text="Just a Test"
如果我们在文本框中输入"te",则文本块中的值应该突出显示为"Just a *Te*st"
在XAML中。
如果有人知道,请告诉我!
提前感谢!

这是因为我正在使用Microsoft.Phone.Userdata.contacts。我的问题相关内容在这里https://dev59.com/qGzXa4cB1Zd3GeqPTGjG。 - Gopinath Perumal
2个回答

8

你好,我在这里找到了解决方案,下面是基于MVVM模式设计的代码:

编辑:**页面 -> MainPage.xaml.cs和ListViewModal已根据您的需求进行更改。

由于在视图模态绑定数据时遇到了一些问题,因此通过在代码后台进行快速响应来解决了该问题。

MainPage.xaml

<phone:PhoneApplicationPage 
x:Class="FirstAppInCSharp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Width="Auto" Height="Auto"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" d:DesignHeight="768" d:DesignWidth="480">

<Grid Name='LayoutRoot'>
    <ListBox Height='500' Width='500' Background='Red'
        Name="ContactList"
        Margin="14,85,14,28" Loaded='ContactList_Loaded'
        Foreground="Black"
        ItemsSource='{Binding ListOftext}'
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel
                    Background='AliceBlue' Height='100' Width='500'
                    Orientation="Horizontal">
                    <TextBlock 
                        FontSize='30'
                        Height='70'
                        Foreground='Black'
                        Text='{Binding DisplayName}' Width='300'
                         />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <TextBox
        Height='72'
        HorizontalAlignment='Left'
        Margin='8,27,0,0'
        Name='textBox1'
        TextChanged='textBox1_TextChanged'
        VerticalAlignment='Top'
        Width='460' />
</Grid>

Now the MainPage.xaml.cs

public partial class MainPage : PhoneApplicationPage
{
    TextBlock textBlock1 = null;
    List<TextBlock> listText = null;
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        Contacts contact = new Contacts();
        contact.SearchAsync("", FilterKind.DisplayName, null);
        contact.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contact_SearchCompleted);
    }
    void contact_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        ContactList.DataContext = new ListViewModal(e.Results);
    }

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        SearchVisualTree(ContactList);

    }


    private void SearchVisualTree(DependencyObject targetElement)
    {

        var count = VisualTreeHelper.GetChildrenCount(targetElement);

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(targetElement, i);
            if (child is TextBlock)
            {
                textBlock1 = (TextBlock)child;
                HighlightText();
                break;
            }
            else
            {
                SearchVisualTree(child);
            }
        }
    }

    private void HighlightText()
    {
        if (textBlock1 != null)
        {
            string text = textBlock1.Text;
            textBlock1.Text = text;
            textBlock1.Inlines.Clear();

            int index = text.IndexOf(textBox1.Text);
            int lenth = textBox1.Text.Length;


            if (!(index < 0))
            {
                Run run = new Run() { Text = text.Substring(index, lenth), FontWeight = FontWeights.ExtraBold };
                run.Foreground = new SolidColorBrush(Colors.Orange);
                textBlock1.Inlines.Add(new Run() { Text = text.Substring(0, index), FontWeight = FontWeights.Normal });
                textBlock1.Inlines.Add(run);
                textBlock1.Inlines.Add(new Run() { Text = text.Substring(index + lenth), FontWeight = FontWeights.Normal });

                textBlock1.FontSize = 30;
                textBlock1.Foreground = new SolidColorBrush(Colors.Black);
            }
            else
            {
                textBlock1.Text = "No Match";
            }
        }

    }

    private void ContactList_Loaded(object sender, RoutedEventArgs e)
    {

    }
}

now the view modal for the list (I have added data manually)

public class ListViewModal : INotifyPropertyChanged
{
    public List<CheckList> ListOftext { get; set; }

    public ListViewModal(IEnumerable<Contact> iEnumerable)
    {
        ListOftext = new List<CheckList>();
        foreach (var list in iEnumerable) 
        {
            ListOftext.Add(new CheckList(){DisplayName = list.DisplayName});
        }
        RaisePropertyChanged("ListOftext");
    }



    /// <summary>
    /// Property changed method
    /// Executes when a property changes its value
    /// </summary>
    /// <param name="propertyName"></param>
    public void RaisePropertyChanged(string propertyName)
    {
        // this is the property changed method 
        //to detect property change
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private IEnumerable<Contact> iEnumerable;
}

now the data binding class (MOdel class)

public class CheckList
{
    public string DisplayName { get; set; }

}

thanks :) you can ask further questions if u want to or if you have any doubts .


这将适用于用户定义的列表,但我不明白如何在列表视图中填充手机联系人列表... - Gopinath Perumal
谢谢您的回复!抱歉打扰您了。能否请您讲一下SearchVisualTree方法... - Gopinath Perumal
你的代码运行良好,但列表只被填充一次。列表不会根据文本更改而改变。 - Gopinath Perumal
2
VisualTreeHelper.GetChild(targetElement, i);这是搜索子元素的主要代码部分。如果您调试应用程序,可以确定该内容如何迭代。实际上,可视化树是以树形结构对元素进行排列的父子关系。我们从父节点即联系人列表开始搜索,并检查每个分支元素。如果未找到该元素,则移动到下一个分支。希望这种解释有所帮助。没有包含技术细节,这样您就可以更容易地理解 :) - Anobik

1
这里是一个样本代码,用于放置在文本框的 TextChange 事件中。
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        string text = "this is a TextBlock";
        textBlock1.Text = text;
        textBlock1.Inlines.Clear();

        int index = text.IndexOf(textBox1.Text);
        int lenth = textBox1.Text.Length;


        if (!(index < 0))
        {
            Run run = new Run() { Text = text.Substring(index, lenth), FontWeight = FontWeights.ExtraBold };
            run.Foreground = new SolidColorBrush(Colors.Orange);
            textBlock1.Inlines.Add(new Run() { Text = text.Substring(0, index), FontWeight = FontWeights.Normal });
            textBlock1.Inlines.Add(run);
            textBlock1.Inlines.Add(new Run() { Text = text.Substring(index + lenth), FontWeight = FontWeights.Normal });

            textBlock1.FontSize = 30;
            textBlock1.Foreground = new SolidColorBrush(Colors.White);
        }
        else 
        {
            textBlock1.Text = "No Match";
        }
    }

这将突出显示文本并返回“未找到匹配项”。

注意:此代码片段区分大小写。


你看到我的问题链接了吗? - Gopinath Perumal
我们不能在数据模板中使用TextBlock。这就是为什么我要求XAML的原因... - Gopinath Perumal
目前我没有系统来检查,但如果可能的话,明天我一定会回答你 :) 我错过了链接,我猜你后来添加了它...或者可能是我错过了 :) - Anobik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接