博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Silverlight小技巧--FrameworkElement.SetBinding Method

Posted on 2010-04-23 13:14  小高好孩子  阅读(1156)  评论(0)    收藏  举报

示例代码如下:

//Create the source string
string s = "Hello";

//Create the binding description
Binding b = new Binding("");
b.Mode = BindingMode.OneTime;
b.Source = s;

//Attach the binding to the target
MyText.SetBinding(TextBlock.TextProperty, b);

示例二:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
namespace TextBoxDemo
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        string valueToSearch;//输入的查询条件
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtNameSearch.Text.Trim()))
            {
                MessageBox.Show("请输入查询条件!");
                return;
            }
            else {
                valueToSearch = txtNameSearch.Text.Trim();
                WebClient client = new WebClient();
                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
               client.DownloadStringAsync(new Uri("../XML/Employees.xml",UriKind.Relative));
            }

        }
        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
          
            XDocument document = XDocument.Parse(e.Result);
            XElement el = XElement.Load(document.CreateReader());
            var items = (
                from item in el.Elements("employess").Elements("item")
                where item.Element("name").Value.StartsWith(valueToSearch)
                select new Employee
                {
                    EName = ((string)item.Element("name")),
                ESex = (string)item.Element("gender") }
                ).Take(1);
            if (items.Count() == 0)
            {
                MessageBox.Show("抱歉,找不到!");
                SPContent.DataContext = null;
            }
            else {
                Employee p = items.ElementAt<Employee>(0);
                System.Windows.Data.Binding binding = new System.Windows.Data.Binding("");
                binding.Mode = System.Windows.Data.BindingMode.OneWay;
                binding.Source = p.EName;
               
                txtName.SetBinding(TextBox.TextProperty,binding );
              
              
               
               
            }
        }
    }
   
    class Employee {
        public string EName { get; set; }
        public string ESex { get; set; }
    }
}