[WPF] DataTemplate Binding to Interface

摘要:[WPF] DataTemplate Binding to Interface

在WPF內可以使用DataTemplate,來輔助完成對物件集合做DataBinding的工作。並且透過DataTemplate的DataType屬性,來讓物件集合中不同的物件,經過DataBinding之後能有「不同的外觀」。簡單的範例如下:不同的車輛類型,會依照車輛類型,呈現不同的詳細資料。



namespace BindingInterfaceSample
{
    public class Car
    {
        public string Name { get; set; }
    }

    public class Truck : Car
    {
        public int MaxLoad { get; set; }
    }

    public class Roadster : Car
    {
        public int MaxSpeed { get; set; }
    }
}


<Window x:Class="BindingInterfaceSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:clk="clr-namespace:BindingInterfaceSample"
        Title="MainWindow" Height="350" Width="525">
    <ItemsControl >
        <ItemsControl.Items>
            <clk:Truck Name="Truck01" MaxLoad="100" />
            <clk:Truck Name="Truck02" MaxLoad="500" />
            <clk:Roadster Name="Roadster01" MaxSpeed="99" />
        </ItemsControl.Items>
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type clk:Truck}">
                <WrapPanel>
                    <TextBlock Text="Truck" />
                    <TextBlock Text="{Binding Path=MaxLoad}" />
                </WrapPanel>
            </DataTemplate>
            <DataTemplate DataType="{x:Type clk:Roadster}">
                <WrapPanel>
                    <TextBlock Text="Roadster" />
                    <TextBlock Text="{Binding Path=MaxSpeed}" />
                </WrapPanel>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
</Window>


反過來說,也可以經由DataTemplate的DataType屬性,來讓物件集合中不同的物件,經過DataBinding之後能有「相同的外觀」。簡單的範例如下:只要是車,都只呈現車的資料。



namespace BindingInterfaceSample
{
    public class Car
    {
        public string Name { get; set; }
    }

    public class Truck : Car
    {
        public int MaxLoad { get; set; }
    }

    public class Roadster : Car
    {
        public int MaxSpeed { get; set; }
    }
}


<Window x:Class="BindingInterfaceSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:clk="clr-namespace:BindingInterfaceSample"
        Title="MainWindow" Height="350" Width="525">
    <ItemsControl >
        <ItemsControl.Items>
            <clk:Truck Name="Truck01" MaxLoad="100" />
            <clk:Truck Name="Truck02" MaxLoad="500" />
            <clk:Roadster Name="Roadster01" MaxSpeed="99" />
        </ItemsControl.Items>
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type clk:Car}">
                <Button Content="{Binding Path=Name}" />
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
</Window>


而在讓物件集合中不同的物件,經過DataBinding之後能有「相同的外觀」。這個使用情景中,DataTemplate的DataType如果設定為Interface型別,在WPF中會出現意外的執行結果。簡單的範例如下:DataType設定為Interface型別,會無法對應DataTemplate。



namespace BindingInterfaceSample
{
    public interface ICar
    {
        string Name { get; set; }
    }

    public class Truck : ICar
    {
        public string Name { get; set; }

        public int MaxLoad { get; set; }        
    }

    public class Roadster : ICar
    {
        public string Name { get; set; }

        public int MaxSpeed { get; set; }
    }
}


<Window x:Class="BindingInterfaceSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:clk="clr-namespace:BindingInterfaceSample"
        Title="MainWindow" Height="350" Width="525">
    <ItemsControl >
        <ItemsControl.Items>
            <clk:Truck Name="Truck01" MaxLoad="100" />
            <clk:Truck Name="Truck02" MaxLoad="500" />
            <clk:Roadster Name="Roadster01" MaxSpeed="99" />
        </ItemsControl.Items>
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type clk:ICar}">
                <Button Content="{Binding Path=Name}" />
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
</Window>


遇到必須設定DataTemplate的DataType為Interface型別的情景。解決的方法很簡單:只要改寫資料繫結容器使用的DataTemplateSelector,增加以Interface型別做索引,查詢Resource裡的DataTemplate,再用這個DataTemplate來做DataBinding。簡單的範例如下:只要是有實做車介面,都只呈現車的資料。



namespace BindingInterfaceSample
{
    public interface ICar
    {
        string Name { get; set; }
    }

    public class Truck : ICar
    {
        public string Name { get; set; }

        public int MaxLoad { get; set; }
    }

    public class Roadster : ICar
    {
        public string Name { get; set; }

        public int MaxSpeed { get; set; }
    }
}


<Window x:Class="BindingInterfaceSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:clk="clr-namespace:BindingInterfaceSample"
        Title="MainWindow" Height="350" Width="525">
    <ItemsControl>
        <ItemsControl.Items>
            <clk:Truck Name="Truck01" MaxLoad="100" />
            <clk:Truck Name="Truck02" MaxLoad="500" />
            <clk:Roadster Name="Roadster01" MaxSpeed="99" />
        </ItemsControl.Items>        
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type clk:ICar}">
                <Button Content="{Binding Path=Name}" />
            </DataTemplate>
        </ItemsControl.Resources>
        <ItemsControl.ItemTemplateSelector>
            <clk:StandardDataTemplateSelector />
        </ItemsControl.ItemTemplateSelector>
    </ItemsControl>
</Window>


namespace BindingInterfaceSample
{
    public class StandardDataTemplateSelector : DataTemplateSelector
    {
        // Methods
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            #region Require

            if (item == null) throw new ArgumentNullException();
            if (container == null) throw new ArgumentNullException();

            #endregion

            // Result
            DataTemplate itemDataTemplate = null;

            // Base DataTemplate
            itemDataTemplate = base.SelectTemplate(item, container);
            if (itemDataTemplate != null) return itemDataTemplate;

            // Interface DataTemplate
            FrameworkElement itemContainer = container as FrameworkElement;
            if (itemContainer == null) return null;

            foreach (Type itemInterface in item.GetType().GetInterfaces())
            {
                itemDataTemplate = itemContainer.TryFindResource(new DataTemplateKey(itemInterface)) as DataTemplate;
                if (itemDataTemplate != null) break;
            }

            // Return
            return itemDataTemplate;
        }
    }
}


參考資料
Style、DataTemplate 和隱含索引鍵
DataTemplateKey 類別


範列下載
BindingInterfaceSample點此下載

期許自己
能以更簡潔的文字與程式碼,傳達出程式設計背後的精神。
真正做到「以形寫神」的境界。