程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Windows 8 Store Apps學習(52) 綁定

Windows 8 Store Apps學習(52) 綁定

編輯:關於.NET

綁定: 與 Element Model Indexer Style RelativeSource 綁定, 以及綁定中的數據轉換

介紹

重新想象 Windows 8 Store Apps 之 綁定

與 Element 綁定

與 Model 綁定

與 Indexer 綁定

對 Style 中的 Setter 進行綁定(綁定靜態資源)

Binding 的一個擴展標記 RelativeSource 的應用

綁定中的數據轉換

示例

1、演示如何與 Element 綁定,以及 OneTime, OneWay, TwoWay 的區別

Binding/BindingElement.xaml

<Page
    x:Class="XamlDemo.Binding.BindingElement"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Binding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">
               
            <!--
                本例用於演示如何與 Element 綁定,以及 OneTime, OneWay, TwoWay 的區別
            -->
                
            <!--
                OneTime 方式綁定元素
            -->
            <Slider Name="sliderOneTime" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" />
            <TextBox Text="{Binding ElementName=sliderOneTime, Path=Value, Mode=OneTime}" Width="150" HorizontalAlignment="Left" />
    
            <!--
                OneWay 方式綁定元素(OneWay 是默認方式)
            -->
            <Slider Name="sliderOneWay" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" Margin="0 50 0 0" />
            <TextBox Text="{Binding ElementName=sliderOneWay, Path=Value, Mode=OneWay}" Width="150" HorizontalAlignment="Left" />
    
            <!--
                TwoWay 方式綁定元素
            -->
            <Slider Name="sliderTwoWay" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" Margin="0 50 0 0" />
            <TextBox Text="{Binding ElementName=sliderTwoWay, Path=Value, Mode=TwoWay}" Width="150" HorizontalAlignment="Left" />
    
        </StackPanel>
    </Grid>
</Page>

2、演示如何與 Model 進行雙向綁定

Binding/BindingModel.xaml

<Page
    x:Class="XamlDemo.Binding.BindingModel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Binding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0" Name="root">
                
            <TextBlock Name="lblMsg" FontSize="14.667" />
                
            <TextBox FontSize="14.667" Text="{Binding Path=Name, Mode=TwoWay}" Margin="0 10 10 0" />
            <TextBox FontSize="14.667" Text="{Binding Age, Mode=TwoWay}" Margin="0 10 10 0" />
            <ToggleSwitch OffContent="女" OnContent="男" Header="性別" Margin="0 10 10 0">
                <ToggleSwitch.IsOn>
                    <Binding Path="IsMale" Mode="TwoWay" />
                </ToggleSwitch.IsOn>
            </ToggleSwitch>
                
        </StackPanel>
    </Grid>
</Page>

Binding/BindingModel.xaml.cs

/*
 * 演示如何與 Model 進行雙向綁定
 */
    
using System;
using System.ComponentModel;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using XamlDemo.Model;
    
namespace XamlDemo.Binding
{
    public sealed partial class BindingModel : Page
    {
        private Employee _employee;
    
        public BindingModel()
        {
            this.InitializeComponent();
    
            this.Loaded += BindingModel_Loaded;
        }
    
        void BindingModel_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // 創建一個需要綁定的實體對象(注:Employee 實現了 INotifyPropertyChanged 接口,想要OneWay 或者 TwoWay 的話必須要實現 INotifyPropertyChanged 接口)
            _employee = new Employee();
            _employee.Name = "webabcd";
            _employee.Age = 33;
            _employee.IsMale = true;
    
            // 每 5 秒更新一次數據
            ThreadPoolTimer.CreatePeriodicTimer(
                (timer) =>
                {
                    var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
                        () =>
                        {
                            Random random = new Random();
                            _employee.Age = random.Next(10, 100);
                            _employee.IsMale = random.Next() % 2 == 0 ? true : false;
                        });
                },
                TimeSpan.FromMilliseconds(5000));
    
            // Employee 對象的屬性的值發生變化時觸發的事件
            _employee.PropertyChanged += _employee_PropertyChanged;
    
            root.DataContext = _employee;
        }
    
        // 每次屬性的值發生變化時,顯示變化後的結果
        void _employee_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            lblMsg.Text = "屬性:“" + e.PropertyName + "”的值發生了變化";
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += string.Format("當前的值為:Name-{0}, Age-{1}, IsMale-{2}", 

_employee.Name, _employee.Age, _employee.IsMale);
        }
    }
}

3、演示如何與索引器進行綁定

Binding/BindingIndexer.xaml

<Page
    x:Class="XamlDemo.Binding.BindingIndexer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Binding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">
    
            <!--演示如何綁定集合中的某個元素-->
            <TextBlock Name="textBlock" FontSize="14.667" Text="{Binding Path=[3] }" />
    
            <!--示如何綁定集合中的某個對象的某個屬性-->
            <TextBlock Name="textBlock2" FontSize="14.667" Text="{Binding Path=[5].Name }" Margin="0 10 0 0" />
    
            <!--演示如何綁定 string 類型的索引器-->
            <TextBlock Name="textBlock3" FontSize="14.667" Text="{Binding Path=[webabcd] }" Margin="0 10 0 0" />
    
            <!--演示如何綁定字典表中指定 key 的數據-->
            <TextBlock Name="textBlock4" FontSize="14.667" Text="{Binding Path=[hello] }" Margin="0 10 0 0" />
    
        </StackPanel>
    </Grid>
</Page>

Binding/BindingIndexer.xaml.cs

/*
 * 演示如何與索引器進行綁定
 */
    
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;
using XamlDemo.Model;
    
namespace XamlDemo.Binding
{
    public sealed partial class BindingIndexer : Page
    {
        public BindingIndexer()
        {
            this.InitializeComponent();
    
            this.Loaded += BindingIndexer_Loaded;
        }
    
        void BindingIndexer_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // 用於演示如何綁定集合中的某個元素
            List<string> list = new List<string>();
            for (int i = 0; i < 10; i++)
            {
                list.Add("索引:" + i.ToString());
            }
            textBlock.DataContext = list;
    
            // 用於演示如何綁定集合中的某個對象的某個屬性
            textBlock2.DataContext = TestData.GetEmployees();
    
            // 用於演示如何綁定 string 類型的索引器
            textBlock3.DataContext = this;
    
            // 用於演示如何綁定字典表中指定 key 的數據
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["hello"] = "hello webabcd";
            textBlock4.DataContext = dic;
        }
    
        // 自定義一個索引器
        public object this[string indexer]
        {
            get
            {
                return indexer;
            }
        }
    }
}

4、演示 Style 中的 Setter 如何做數據綁定(綁定靜態資源)

Binding/BindingStyleSetter.xaml

<Page
    x:Class="XamlDemo.Binding.BindingStyleSetter"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Binding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">
    
            <!--
                演示 Style 中的 Setter 如何做數據綁定
            -->
                
            <StackPanel.Resources>
                <!--設置一些資源-->
                <x:Double x:Key="TextFontSize">24.667</x:Double>
                <SolidColorBrush x:Key="TextForeground" Color="#00FF00" />
    
                <!--為 Style 的 Setter 的 Value 做數據綁定-->
                <Style x:Key="MyStyle" TargetType="TextBox">
                    <Setter Property="FontSize" Value="{Binding Source={StaticResource TextFontSize}}"/>
                    <Setter Property="Foreground" Value="{Binding Source={StaticResource TextForeground}}"/>
                </Style>
            </StackPanel.Resources>

    
            <!--應用樣式-->
            <TextBox Text="我是TextBox" Style="{StaticResource MyStyle}" />
    
        </StackPanel>
    </Grid>
</Page>

5、演示 Binding 中的一個擴展標記 RelativeSource 的應用

Binding/BindingRelativeSource.xaml

<Page
    x:Class="XamlDemo.Binding.BindingRelativeSource"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Binding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">
    
            <!--
                演示 Binding 中的一個擴展標記 RelativeSource 的應用,其用於指定關聯數據源為 Self 或 TemplatedParent
                另外簡要說明 TemplateBinding 的應用
            -->
                
            <StackPanel.Resources>
                <Style x:Key="MyStyle" TargetType="Button">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="Button">
                                <StackPanel>
                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" />
                                    <!--
                                        TemplateBinding 是一個簡單版的 Binding,用於在模板中綁定控件的某個屬性
                                        
                                        如果設計模板時需要用到雙向綁定,則 TemplateBinding 就無能為力了(TemplateBinding 是 OneWay 的)
                                        只能通過 Binding 來做雙向綁定,然後通過 RelativeSource={RelativeSource TemplatedParent} 指定數據源來自引用了該 ControlTemplate 的 Control
                                    -->
                                    <Slider Minimum="1" Maximum="100" Width="{TemplateBinding Width}" Value="{Binding Content, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" 

/>
                                </StackPanel>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </StackPanel.Resources>
    
            <Button Width="300" Content="10" Style="{StaticResource MyStyle}" />
    
                
            <!--
                RelativeSource={RelativeSource Self} - 指定數據源為自己本身
            -->
            <TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" Tag="webabcd" FontSize="14.667" Margin="0 10 0 0" />
    
        </StackPanel>
    </Grid>
</Page>

6、演示如何在綁定中做數據轉換

Binding/IntegerLetterConverter.cs

/*
 * 繼承 IValueConverter 以實現一個“整數-字母”轉換器
 */
    
using System;
using Windows.UI.Xaml.Data;
    
namespace XamlDemo.Binding
{
    public sealed class IntegerLetterConverter : IValueConverter
    {
        /// <summary>
        /// 正向轉換器。將值從數據源傳給綁定目標時,數據綁定引擎會調用此方法
        /// </summary>
        /// <param name="value">轉換之前的值</param>
        /// <param name="targetType">轉換之後的類型</param>
        /// <param name="parameter">轉換器所使用的參數(它是通過 Binding 的ConverterParameter 傳遞過來的)</param>
        /// <param name="language">轉換器所使用的區域信息(它是通過 Binding 的 ConverterLanguage 傳遞過來的)</param>
        /// <returns>轉換後的值</returns>
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if ((double)value == 1)
                return "a";
            else if ((double)value == 2)
                return "b";
            else if ((double)value == 3)
                return "c";
            else
                return "unknown";
        }
    
        /// <summary>
        /// 反向轉換器。將值從綁定目標傳給數據源時,數據綁定引擎會調用此方法
        /// </summary>
        /// <param name="value">轉換之前的值</param>
        /// <param name="targetType">轉換之後的類型</param>
        /// <param name="parameter">轉換器所使用的參數(它是通過 Binding 的 ConverterParameter 傳遞過來的)</param>
        /// <param name="language">轉換器所使用的區域信息(它是通過 Binding 的 ConverterLanguage 傳遞過來的)</param>
        /// <returns>轉換後的值</returns>
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if ((string)value == "a")
                return 1;
            else if ((string)value == "b")
                return 2;
            else if ((string)value == "c")
                return 3;
            else
                return 1;
        }
    }
}

Binding/ValueConverter.xaml

<Page
    x:Class="XamlDemo.Binding.ValueConverter"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Binding"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">
    
            <!--配置 IValueConverter 資源-->
            <StackPanel.Resources>
                <local:IntegerLetterConverter x:Key="IntegerLetterConverter"/>
            </StackPanel.Resources>
    
            <Slider Name="slider" Minimum="1" Maximum="3" Value="1" Width="180" HorizontalAlignment="Left" />
            <TextBox Width="150" HorizontalAlignment="Left"
                     Text="{Binding Value, 
                                    Mode=TwoWay, 
                                    ElementName=slider, 
                                    Converter={StaticResource IntegerLetterConverter},
                                    ConverterParameter=param, 
                                    ConverterLanguage=zh_cn}" />
    
            <!--注:ConverterParameter 和 ConverterLanguage 不能實現動態的綁定,只能傳遞靜態的參數-->
    
        </StackPanel>
    </Grid>
</Page>

OK

[源碼下載]:http://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved