简体   繁体   English

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

[英]How to write check if a TextBlock consists a specific string in windows phone 7 XAML?

I've have a textblock and a textbox, I need to check and whether the textblock contains the textbox value, if yes then that specific value should be highlighted in some color. 我有一个文本块和一个文本框,我需要检查文本块是否包含文本框值,如果是,那么该特定值应以某种颜色突出显示。 . .

For example, 例如,

TextBlock.Text="Just a Test" TextBlock.Text =“只是一个测试”

if we type "te" in TextBox, then the value in the textblock should be highlight as "Just a * Te *st" 如果我们在TextBox中键入“te”,那么textblock中的值应突出显示为“Just a * Te * st”

in xaml. 在xaml。

if anybody know means please say! 如果有人知道手段请说!

Thanks in Advance! 提前致谢!

Hi i found the solution here's the underlying code that has been designed in MVVM pattern : EDIT : ** Pages -> MainPage.xaml.cs and ListViewModal has been changed according to ur need . 您好我发现这里的解决方案是基于MVVM模式设计的底层代码:编辑:**页面 - > MainPage.xaml.cs和ListViewModal已根据您的需要进行了更改。

** was having some issue binding data from view modal so gave a quick response by doing it in code behind **有一些问题从视图模式绑定数据,因此通过在代码后面执行它来快速响应

MainPage.xaml 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 现在是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) 现在的数据绑定类(MOdel类)

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

}

thanks :) you can ask further questions if u want to or if you have any doubts . 谢谢:)你可以提出进一步的问题,如果你想或如果你有任何疑问。

Heres a sample code to be put in the text box TextChange event 下面是一个示例代码,放在文本框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";
        }
    }

this will highlight the text and return no match is no match is found. 这将突出显示文本并返回没有匹配,找不到匹配项。

note : this code snippet is case sensitive. 注意 :此代码段区分大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM