WPF 自定义结构,

若要绑定到附加属性,应在附加属性周围放置圆括号。例如,若要绑定到附加属性
DockPanel..::.Dock,则语法是 Path=(DockPanel.Dock)

1.WPF界面可引用的自定义结构

     界面只能绑定公共属性,如果是引用其它应用程序的话要先用clr-namespace映射命名空间。

    public class Product:INotifyPropertyChanged
    {
        //////////////// 这里缺少PropertyChanged相关的代码的话,在动态修改内存时,不会反应到界面上
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }
        ////////////////////////////////////////////////////////

        private string modelNumber;
        public string ModelNumber
        {
            get { return modelNumber; }
            set { 
                modelNumber = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ModelNumber"));
            }
        }

        private string modelName;
        public string ModelName
        {
            get { return modelName; }
            set { 
                modelName = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ModelName"));
            }
        }

        private decimal unitCost;
        public decimal UnitCost
        {
            get { return unitCost; }
            set { 
                unitCost = value;
                OnPropertyChanged(new PropertyChangedEventArgs("UnitCost"));
            }
        }

        private string description;
        public string Description
        {
            get { return description; }
            set { 
                description = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Description"));
            }
        }

        public Product(string modelNumber, string modelName,
            decimal unitCost, string description)
        {
            ModelNumber = modelNumber;
            ModelName = modelName;
            UnitCost = unitCost;
            Description = description;
        }
    }
    public class StoreDB
    {
        public Product GetProduct(int ID)
        {
            return new Product(ID.ToString(), ID.ToString(), 0, ID.ToString());
        }
    }

 

2,绑定数据源

非列表:
        Product dct;
        dct = this.StoreDB.GetProduct(1);
        userWnd.gridProductDetails.DataContext = dct;
列表:
        List<Product> ducts = new List<Product>();
        for (int i = 0; i < 10; ++i )
            ducts.Add(this.StoreDB.GetProduct(1));
        userWnd.myListBox.ItemsSource = ducts;
若要想列表拥有更改通知控件的功能则需要用如下:
ObservableCollection BindingList 都实现了INotifyCollectionChanged接口,拥有通知控件更改功能。
ObservableCollection        System.Collections.ObjectModel;
BindingList             System.ComponentModel;

      ObservableCollection<Product> ducts = new ObservableCollection<Product>();

      BindingList<Product> ducts = new BindingList<Product>();

 
列表绑定:
当一个列表无素被绑定到容器上时,对于列表,可以显示所有项,对于单个对于支持绑定到列表上的元素(如 列表框,,会绑定整个列表。对于只支持绑定一个对象上的元素(如 文本框),只绑定当前项。容器会有一个当前元素的索引,IsSynchronizedWithCurrentItem可以同步当前索引元素从而达到其它绑定的无素也会变化。
<DockPanel x:Name="myGrid" DataContext="{StaticResource MyDataProvider}">
        <ListBox  DockPanel.Dock="Bottom" Grid.Row="0"  ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"></ListBox>
        <TextBox Text="{Binding ModelNumber}"  Grid.Row="0" Margin="5"/>
        <TextBox Text="{Binding ModelName}"  Grid.Row="1" />
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition  Height="Auto"/>
                <RowDefinition  Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBox Text="{Binding ModelNumber}"  Grid.Row="0" Grid.Column="1" Margin="5" />
            <TextBox Text="{Binding ModelName}" Grid.Row="1" Grid.Column="1" Margin="5" />
        </Grid>
    </DockPanel>

//TreeView  树列表绑定实时更新方式  其它控件可参考这两种方式
<TreeView ItemsSource="{Binding Source={StaticResource myEmployeeData}, XPath=EmployeeInfo}" Name="myTreeView" SelectedValuePath="EmployeeNumber" /> <TextBlock Height ="25" Margin="10,0,0,0" Text="{Binding ElementName=myTreeView,Path=SelectedValue}"Foreground="Blue"/>

      <TextBlock Height=" 30" Text="{Binding ElementName=treeView0,Path=SelectedValue.key}"/>


ObjectDataProvider 绑定:
   <ObjectDataProvider x:Key="DATA_TreeViewList"  ObjectType="{x:Type local:ListKeyFactory}" MethodName="GetKeys"/>
    <ObjectDataProvider x:Key="DATA_TreeViewList1"  ObjectType="{x:Type local:ListLeagueList}"/>
WPF控件多对一的绑定

<Window.Resources>
        <local:HasSelectionNICAndProfileConverter x:Key="HasSelectionNICAndProfileConverter"/>
    </Window.Resources>
<ListBox x:Name="ListBox1" ItemsSource="{Binding}"/>
<TreeView x:Name="Tree1" ItemsSource="{Binding }" ItemTemplate="{StaticResource TemplateX}"/>
<TextBox x:Name="ThyBox" >
    <TextBox.Text>
         <MultiBinding Converter="{StaticResource HasSelectionNICAndProfileConverter}" Mode="OneWay">
              <Binding ElementName="ListBox1" Path="SelectedItem"/>
              <Binding ElementName="Tree1" Path="SelectedItem"/>
         </MultiBinding>
    </TextBox.Text>
 </TextBox>


public class HasSelectionNICAndProfileConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            object NICSelection = values[0];
            object ProfileSelection = values[1];
            if (NICSelection != null && ProfileSelection != null) return "Selected";
            else return "UNSelected";
        }
        public object[] ConvertBack(object values, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
这里的代码实现了,只有当两个TreeView同时有项被选中时,TextBlock中才会显示Selected。

 

3.数据转换

    public class MyConvert : IValueConverter
    {
        #region IValueConverter 成员
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.GetType() == typeof(TextBox))
                return ((decimal)value).ToString("C");

            return null;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string mypric = value.ToString();
            decimal pri;
            if (decimal.TryParse(mypric, System.Globalization.NumberStyles.Any, culture, out pri))
            {
                return pri;
            }
            return value;
        }
        #endregion
    }

<local:MyConvert x:Key="DATA_TreeViewSelectItemConvert"></local:MyConvert>

<TextBlock Height=" 30" Text="{Binding Source=(treeView0.Item.TextBox), Converter={StaticResource DATA_TreeViewSelectItemConvert}}"/>      //指定绑定转换器

<MultiBinding Converter="{StaticResource myNameConverter}" ConverterParameter="FormatLastFirst">

 3.切换控件风格(可以定义不同外观的风格)

            object var = FindResource("CtrlStyleComboBox");
            if (var != null && var.GetType() == typeof(Style))
                comboxxxxxx.Style = var as Style;
//获取控件默认风格

<Style x:Key="CtrlStyleComboBox1" TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>

 3.XmlDataProvider定义

 <XmlDataProvider x:Key="xmlProder" XPath="/Items/*">
            <x:XData>
                <Items  xmlns="">  //xmlns=""一定要加,上面XPath指定了导出Items下的所有集合,即一个列表  每个标签可以作为类型名直接XPath=Type引用,而属性则要用XPath=@Name
                    <Item Name="000" ShortCut="aaa">
                        <combox Name="000"/>
                        <combox Name="001"/>
                        <combox Name="002"/>
                        <combox Name="003"/>
                        <combox Name="004"/>
                        <combox Name="005"/>
                    </Item>
                    <Item Name="001" ShortCut="bbb">
                        <combox Name="000"/>
                        <combox Name="001"/>
                        <combox Name="002"/>
                        <combox Name="003"/>
                        <combox Name="004"/>
                        <combox Name="005"/>
                    </Item>
                    <Item Name="002" ShortCut="ccc">
                        <combox Name="000"/>
                        <combox Name="001"/>
                        <combox Name="002"/>
                        <combox Name="003"/>
                        <combox Name="004"/>
                        <combox Name="005"/>
                    </Item>
                </Items>
            </x:XData>
        </XmlDataProvider>

 4.ICommand接口的使用

C#方式  设计并不好,仅代表如何使用而已。
  public RoutedCommand cmd;
        public MainWindow()
        {
            InitializeComponent();

            cmd = new RoutedCommand();
            CommandBinding bind = new CommandBinding(cmd);
            bind.Executed += Execute;
            bind.CanExecute += CanExecute;

            this.CommandBindings.Add(bind);

            _myButton.Command = cmd;
        }

        public void CanExecute(object parameter, CanExecuteRoutedEventArgs e)
        {
            if (_myBox.Text == null || _myBox.Text == "")
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
        }

        private void Execute(object parameter, ExecutedRoutedEventArgs e)
        {
            string msg = "引发事件的类型:{0},命令目标的类型:{1},命令目标的Name:{2}";
            System.Diagnostics.Debug.WriteLine(
                    string.Format(msg,
                                  parameter.GetType().Name,
                                  e.Source.GetType().Name,
                                  (e.Source as FrameworkElement).Name
                ));  

            MessageBox.Show(_myBox.Text);
        }
xaml方式:仅代表如何使用
    public class CMDClass
    {
        public static RoutedCommand cmd;
        static CMDClass()
        {
            cmd = new RoutedCommand();
        }
        public void CanExecute(object parameter, CanExecuteRoutedEventArgs e)
        {
            if (_myBox.Text == null || _myBox.Text == "")
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
        }
        private void Execute(object parameter, ExecutedRoutedEventArgs e)
        {
            string msg = "引发事件的类型:{0},命令目标的类型:{1},命令目标的Name:{2}";
            System.Diagnostics.Debug.WriteLine(
                    string.Format(msg,
                                  parameter.GetType().Name,
                                  e.Source.GetType().Name,
                                  (e.Source as FrameworkElement).Name
                ));
            MessageBox.Show(_myBox.Text);
        }
    }
  <Window.CommandBindings>
        <CommandBinding Command="local:CMDClass.cmd" Executed="Execute" CanExecute="CanExecute"/>
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBox Name="_myBox"  Grid.Row="0"  Text="我是个好学生!"/>
        <Button Name="_myButton"  Grid.Row="1" Command="local:CMDClass.cmd"/>
    </Grid>

 

posted @ 2014-06-15 00:25  高_山_流_水  阅读(302)  评论(0)    收藏  举报