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

Gop*_*mal 4 c# xaml windows-phone-7

我有一个文本块和一个文本框,我需要检查文本块是否包含文本框值,如果是,那么该特定值应以某种颜色突出显示...

例如,

TextBlock.Text ="只是一个测试"

如果我们在TextBox中键入"te",那么textblock中的值应突出显示为"Just a*Te*st"

在xaml.

如果有人知道手段请说!

提前致谢!

Ano*_*bik 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>
Run Code Online (Sandbox Code Playgroud)

现在是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)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

现在列表的视图模式(我手动添加了数据)

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;
}
Run Code Online (Sandbox Code Playgroud)

现在的数据绑定类(MOdel类)

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

}
Run Code Online (Sandbox Code Playgroud)

谢谢:)你可以提出进一步的问题,如果你想或如果你有任何疑问.

  • VisualTreeHelper.GetChild(targetElement,i); 这是搜索子元素的代码的主要部分.如果你调试你的应用程序你可以识别事物如何迭代可视树实际上是元素在树结构中作为子和父对齐.我们从父节点开始搜索..这是联系人列表并检查每个分支元素.如果找不到元素,那么我们移动到下一个分支.希望这个解释有所帮助 没有包含技术性,你会更容易理解:) (2认同)