WPFとデータバインディング

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
JIBA

WPFとデータバインディング

#1

投稿記事 by JIBA » 7年前

MS WindowsのWPF機能があって、データバインディング をサポートします。
そのため、XAMLの中に以下のような記述が必要ですが、
その中の「x:Key="colorConverter"」の存在意味は分かりません。

<Window x:Class="BindingTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006 ... esentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:BindingTest"
Title="Binding" Height="300" Width="300">
<Window.Resources>
<c:ColorConverter x:Key="colorConverter" />

=====================
ご存知の方ご説明お願いします.

それから、XMLと関係するーーーXMLへserializationの技術も「データバインディング」というのですが、
この2種類のデータバインディングは関係ない技術ですね?

metaphor

Re: WPFとデータバインディング

#2

投稿記事 by metaphor » 7年前

x:Key="colorConverter”はC#とかVisualBasicのオブジェクトとして扱える様にする為です。”WPF"のみではなく”Form"でもデータバインディング をサポートします。XMLへserialization-->XAMLへserializationもつかわれますよ。

あんどーなつ
記事: 171
登録日時: 7年前
連絡を取る:

Re: WPFとデータバインディング

#3

投稿記事 by あんどーなつ » 7年前

下記ページに類似したコードがあります。

http://www.kanazawa-net.ne.jp/~pmansato ... inding.htm

WPFは情報が少ないのでC#が初めての人にはお勧めできないです。Windowsフォームがある程度使えるようになってからじゃないとダメです。

Kindleで「プログラミングWindows第6版」は読まれてますか?最初のほうの章は無料で読めますのでWPFに興味がありましたら、そちらを読んでみてください。
(追記:注意) 「プログラミングWindows第6版」はWindowsストアアプリ(*)のための本です。WPFを学習する際は、Microsoftの荒井省三さんのBlogの方も併読する必要があります。

XMLのほうのデータバインディングは把握してないです。

(*) (追記2) Windowsアプリ → Windowsストアアプリ
最後に編集したユーザー あんどーなつ on 2016年12月16日(金) 16:08 [ 編集 2 回目 ]

metaphor

Re: WPFとデータバインディング

#4

投稿記事 by metaphor » 7年前

>この2種類のデータバインディングは関係ない技術ですね?
そうです。(「XMLへserializationの技術も「データバインディング」というのですが」はあまり聞きません)

YuO
記事: 947
登録日時: 13年前
住所: 東京都世田谷区

Re: WPFとデータバインディング

#5

投稿記事 by YuO » 7年前

JIBA さんが書きました: その中の「x:Key="colorConverter"」の存在意味は分かりません。
リソースとしてBindingTest.ColorConverterを利用するために記述します。

おそらく,後の方で

コード:

Background="{binding BackColor, Mode=OneWay, Converter={StaticResource colorConverter}}"
のような使い方をしているかと思います。
ここで,Binding.ConverterとしてBindingTest.ColorConverterを使うために,Resource内でクラスにx:Keyを付与しています。
metaphor さんが書きました:x:Key="colorConverter”はC#とかVisualBasicのオブジェクトとして扱える様にする為です。
x:Nameのことでしょうか。

metaphor

Re: WPFとデータバインディング

#6

投稿記事 by metaphor » 7年前

あ、そうです。まだxamlのヘッダー部分でした。失礼いたしました。WPFはC#、VBでMVVMの基本の様なのも作りデータバインディングの便利さは知っています。(xamlはWindows 10 のユニバーサル Windows プラットフォーム (UWP)へ流れ、いまはUWPのゲームを作ったりしてます。)WPFの方がFormよりデータバインディングが便利ですね。

JIBA

Re: WPFとデータバインディング

#7

投稿記事 by JIBA » 7年前

お返答ありがとうございます。

JIBA さんが書きました:
その中の「x:Key="colorConverter"」の存在意味は分かりません。

YuO さんが書きました:
リソースとしてBindingTest.ColorConverterを利用するために記述します。

でも、バイナリコード(コンパイルすれば)としてのBindingTest.ColorConverterとテキストの文字列"colorConverter"とをどうやって関連付けられるのでしょうか。

あんどーなつ
記事: 171
登録日時: 7年前
連絡を取る:

Re: WPFとデータバインディング

#8

投稿記事 by あんどーなつ » 7年前

JIBA さんが書きました: でも、バイナリコード(コンパイルすれば)としてのBindingTest.ColorConverterとテキストの文字列"colorConverter"とをどうやって関連付けられるのでしょうか。
すみません、ご質問の意味がよく分からないです。先ほど私が示したサイト、

http://www.kanazawa-net.ne.jp/~pmansato ... inding.htm

の、複合データバインディングの項で説明させていただきますと、Slider.ValueはDouble型ですが、それをColor型に変換して使いたいからC#で自前の変換クラスを作って、Window.Resourcesにぶらさげている、Sliderはその変換インスタンスを参照している、ので無駄はないと思います。

ILコードの中にcolorConverterというものがないんだけれども、コンパイラは何をやっているのか、というご質問だとすると私の方ではわかりかねます。

metaphor

Re: WPFとデータバインディング

#9

投稿記事 by metaphor » 7年前

C#とかVBのプログラムを組まないとわからないと思いますが「名前空間System.Windows.DataにあるIValueConverterインターフェースを実装する」ことで値コンバーターを作成することができます。データバインディングしたsliderの実数値をRGBの0~255に変換する例などをみかけます。C#かVBでクラスを作らないと分かりにくいです。

metaphor

Re: WPFとデータバインディング

#10

投稿記事 by metaphor » 7年前

私が以前にC#で作ったサンプルです。

コード:

ConverterWindow x:Class="MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:c="clr-namespace:"

        Title="MainWindow" Height="180" Width="300"
         Loaded="MainWindow_Loaded">
 
  <Window.Resources>

    <c:IntToHexValueConverter x:Key="valueConverter" />

  </Window.Resources>

  <StackPanel Orientation="Vertical">
    <TextBox Name="textBox1" Width="100" Height="25" HorizontalAlignment="Left" Margin="30,10,0,0"

             Text="{Binding ElementName=slider1, Path=Value, Converter={StaticResource valueConverter}}"/>

    <Slider Name="slider1" Height="22" Margin="30,20,60,0" Maximum="255" Minimum="0"
            TickPlacement="TopLeft" TickFrequency="16" SmallChange="1" LargeChange="16"
            IsSnapToTickEnabled="True" />
  </StackPanel>

</Window>

コード:

[ValueConversion(typeof(double), typeof(int))]
public class IntToHexValueConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    double textValue = (double)value;

    return String.Format("{0} (0x{1:X2})", (int)textValue, (int)textValue);
  }
  
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return Binding.DoNothing;
  }
}

sleep

Re: WPFとデータバインディング

#11

投稿記事 by sleep » 7年前

JIBA さんが書きました: その中の「x:Key="colorConverter"」の存在意味は分かりません。
JIBA さんが書きました: でも、バイナリコード(コンパイルすれば)としてのBindingTest.ColorConverterとテキストの文字列"colorConverter"とをどうやって関連付けられるのでしょうか。
Window.Resources は、static readonly で宣言された ResourceDictionary のオブジェクトを返すプロパティです。
key と value をセットとした DictionaryEntry として ResourceDictionary 内部の Hashtable へ値を保存します。
x:Key で定義した "colorConverter" はその key として使用されます。

以下のように書くと分かりますかね?(MainWindow.xaml.cs の 28行目)

MainWindow.xaml

コード:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Mode=OneTime}"
        MouseLeftButtonDown="Window_MouseLeftButtonDown"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!--<local:ColorConverter x:Key="colorConverter"/>-->
    </Window.Resources>
    <Grid>
        <Ellipse Fill="{Binding Path=Switching, Converter={StaticResource colorConverter}}"/>
    </Grid>
</Window>
MainWindow.xaml.cs

コード:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            this.Resources.Add("colorConverter", new ColorConverter());

            InitializeComponent();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Switching = !Switching;
        }

        private bool switching;
        public bool Switching
        {
            get { return switching; }
            set { switching = value; OnPropertyChanged(); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    class ColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var switching = (bool)value;
            return switching ? Brushes.Red : Brushes.Blue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

sleep

Re: WPFとデータバインディング

#12

投稿記事 by sleep » 7年前

訂正です。(「static readonly で宣言された」は消し忘れです。)
sleep さんが書きました: Window.Resources は、static readonly で宣言された ResourceDictionary のオブジェクトを返すプロパティです。
Window.Resources は、ResourceDictionary のオブジェクトを返すプロパティです。
オフトピック
実際は、static readonly で宣言された UncommonField<ResourceDictionary> に、自身(ここでは MainWindow のオブジェクト)を key として ResourceDictionary が格納されていて、それが使用されるわけですが、そんな細かい話はここでは関係ないので忘れてください。

metaphor

Re: WPFとデータバインディング

#13

投稿記事 by metaphor » 7年前

>でも、バイナリコード(コンパイルすれば)としてのBindingTest.ColorConverterとテキストの文字列"colorConverter"とをどうやって関連付けられるのでしょうか。
[この疑問]の意味がわかりました。上の方のプログラムは見ればわかるようにMainWindow.xamlとMainWindow.xaml.csは同じクラスで partial class (分割して書いてあるだけ)です。(WPFでは、XAMLコードからBAMLコードとC#コードを生成)結果的には1つのクラスです。http://www.atmarkit.co.jp/ait/articles/ ... ws101.html

metaphor

Re: WPFとデータバインディング

#14

投稿記事 by metaphor » 7年前

他の方が書かれている28行のthisがこのクラスを示しています。

コード:

public MainWindow()
        {
            this.Resources.Add("colorConverter", new ColorConverter());
 
            InitializeComponent();
        }
その下にあるInitializeComponent();ですがその実装は

コード:

            InitializeComponent();
xaml側に書かれています。

横から

Re: WPFとデータバインディング

#15

投稿記事 by 横から » 7年前

sleep さんが書きました: Window.Resources は、static readonly で宣言された ResourceDictionary のオブジェクトを返すプロパティです。
key と value をセットとした DictionaryEntry として ResourceDictionary 内部の Hashtable へ値を保存します。
x:Key で定義した "colorConverter" はその key として使用されます。
metaphor さんが書きました:>でも、バイナリコード(コンパイルすれば)としてのBindingTest.ColorConverterとテキストの文字列"colorConverter"とをどうやって関連付けられるのでしょうか。
(WPFでは、XAMLコードからBAMLコードとC#コードを生成)結果的には1つのクラスです。http://www.atmarkit.co.jp/ait/articles/ ... ws101.html
この掲示板に本当にすごい方がいらっしゃますね!
感心しました。
(横からすみません)

横から

Re: WPFとデータバインディング

#16

投稿記事 by 横から » 7年前

metaphor さんが書きました: >でも、バイナリコード(コンパイルすれば)としてのBindingTest.ColorConverterとテキストの文字列"colorConverter"とをどうやって関連付けられるのでしょうか。

WPFでは、XAMLコードからBAMLコードとC#コードを生成)結果的には1つのクラスです。
要はXAMLファイルは通常のXMLファイルと違って、単にデータ設定用のテキストファイル(E.g., *.ini ファイル)ではなくて、
C# source codeを生成するスクリプトのような役ですね。

(横からすみません)

metaphor

Re: WPFとデータバインディング

#17

投稿記事 by metaphor » 7年前

その通りです!

metaphor

Re: WPFとデータバインディング

#18

投稿記事 by metaphor » 7年前

(つけ加えるとxamlはVisual Basicの場合”VBのコードを生成するスクリプト"と言えます。)Formデザイナーの役割りをしています。(違うのは「DirectXを使っている」ことと「HTMLの書き方の真似」をしていることです。

コード:

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

コード:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
などに置き換わります。(最初はだれも”ウソ"と思います。) 

JIBA

Re: WPFとデータバインディング

#19

投稿記事 by JIBA » 7年前

皆さんご教授本当にありがとうございます。
metaphor さんが書きました:他の方が書かれている28行のthisがこのクラスを示しています。

コード:

public MainWindow()
        {
            this.Resources.Add("colorConverter", new ColorConverter());
 
            InitializeComponent();
        }
その下にあるInitializeComponent();ですがその実装は

コード:

            InitializeComponent();
xaml側に書かれています。
頭が良くなくてすみません、
下の文(From metaphor様)によって、

コード:

 this.Resources.Add("colorConverter", new ColorConverter()); 
Key="colorConverter" とBindingTest.ColorConverter が関連付けられたのでしょうか。

また宜しくお願いします

metaphor

Re: WPFとデータバインディング

#20

投稿記事 by metaphor » 7年前

核心に近づくとプログラムの知識がいります。

コード:

xmlns:c="clr-namespace:BindingTest"
 Title="Binding" Height="300" Width="300">
 <Window.Resources>
 <c:ColorConverter x:Key="colorConverter" />
BindingTestが何者か?xmlns:c="clr-namespace:BindingTest"によって名前空間namespaceです。
そこに所属するクラスがthisです。
this.Resources.Add("colorConverter", new ColorConverter());でインスタンスがつくられます。それがResources加えられます。
(多分プログラムをしないとわかりずらいです)











JIBA

Re: WPFとデータバインディング

#21

投稿記事 by JIBA » 7年前

おかげさまで、原理的にある程度分かったような気がしますが、
自分当初の感覚とは随分違います。
自分の認識としてWPFはGUI formのデザインがエンドユーザが「テキスト(XAML)」編集で自由に変更できる(開発環境要らない)というアイディアであると思っていました。

皆様の解説からすれば、そうでもなく、XAMLに対してコンパイルし、C#ソースコードを生成し、
当然生成されたC#ソースコードを開発環境でコンパイルする必要になりますね。

Q1. 実際、だんなコンパイラーでXAMLを処理するのでしょうか。
Q2. 個人的に、XAMLの記述法はC言語よりくどくどしい、メリットはなんでしょうか。

metaphor

Re: WPFとデータバインディング

#22

投稿記事 by metaphor » 7年前

Q1. 実際、どんなコンパイラーでXAMLを処理するのでしょうか。
C#とVBとC++とF#などです。Blendというのがデザイナーさん用にあります。(私はVS2015を使っていて全部VS2015に付属をしています)簡単なものはWindows付属のPowerShellで作って動かせます。私は最初はWindowsだけでかなりの数のxaml(ザムル)を作りました。簡単なアプリケーションはxamlだけで完結します。DirectXで図形描画もかんたんです。
Q2. 個人的に、XAMLの記述法はC言語よりくどくどしい、メリットはなんでしょうか。
それは何かの誤解で小学生でもかけます。「記述法はC言語よりくどくどしい」は逆です(^^。HTMLをまねて簡単にしたものでデザイナーさん向けにプログラムの知識がいらないというメリットがあります。
(Windowsさえあれば使えるので実行してみれば少ないコードで複雑なことができます。サンプルはサイトに沢山あります)

YuO
記事: 947
登録日時: 13年前
住所: 東京都世田谷区

Re: WPFとデータバインディング

#23

投稿記事 by YuO » 7年前

根本的な勘違いがありそうですが……。

XAMLは,本質的にオブジェクトのシリアライズ表現の一つです。
WPFだけでなくWF (Windows Workflow Foundation) などでも用いられた技術です。
# 最近WFがどうなっているか知らない&元々WFはXAMLでなくてもよかったので,とりあえず過去形の表現。

JIBA さんが書きました:自分の認識としてWPFはGUI formのデザインがエンドユーザが「テキスト(XAML)」編集で自由に変更できる(開発環境要らない)というアイディアであると思っていました。
リソースにはなるものの,基本的にはそのような修正はできません。

ただし,XAML自体を読み込むためにXamlReader クラスが存在し,このクラスを使うと実行時にXAMLを読み込んでオブジェクトを生成する事ができます。
生成されたオブジェクトをWPFのオブジェクトツリーに追加することで,似たようなことは可能にはなります。
ただし,これデザインの変更を行っても,データをどこに表示するのか,などのマーカーが必要になります。
データバインディングを書いておくとちゃんとバインディングごとデシリアライズされるのですが,これをエンドユーザーが書けるか,というと難しいでしょう。
そのような理由から,エンドユーザーが直接XAMLを弄って,というのは現実的ではありません。

JIBA さんが書きました:Q2. 個人的に、XAMLの記述法はC言語よりくどくどしい、メリットはなんでしょうか。
くどいと感じるかは慣れですが,UIとコードの分離によって,複雑なことが読みやすくなります。

WPFではXAMLをDSL (Domain Sepcific Language: 目的に特化した言語) として利用しています。
なので,XAMLにはUIの部分しか(基本的には)書かれていません。
このことは,UIを修正しようと思った場合には基本的にXAMLを修正すればよい,ということになります。
オフトピック
x:Codeという話をややこしくする機構があるのですが,
これは普通使われない,というか知られていないし忘れられています。
また,XMLでユーザーが修正できるため,Windows Formsの.designer.csのように,一部修正をしたら順序が入れ替わってgit等の変更履歴が不用意に汚される心配もありません。


あと,勘違いされていそうなので書きますが,

コード:

<Window.Resources>
    <c:ColorConverter x:Key="colorConverter" />
</Window.Resources>

コード:

this.Resources.Add("colorConverter", new ColorConverter());
になるわけではありません。
No.11のsleepさんの記事の,MainWindow.xamlの15行目は,
sleep さんが書きました:

コード:

        <!--<local:ColorConverter x:Key="colorConverter"/>-->
と,コメントアウトされています。
コメントにしたからコンストラクタで上記に相当することを書いているだけで,XAML側で定義したならば実際には.NET Frameworkの内部で処理されます。
オフトピック
Refernece Sourceを読み込んでいけば,たぶんResources.Add相当が見つかると思いますが……。
XAMLが実際にはどのような実装によって処理されているのか,というのはWPFを使う上ではとりあえず必要のない情報になります。
必要ならば上記のReference Sourceを読めばよいのですが,それを知る事が意味を持つのは非常に限られた,一部の人だけだと思います。

metaphor さんが書きました:

コード:

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

コード:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
などに置き換わります。(最初はだれも”ウソ"と思います。) 
置き換わらないし,そもそもC#のusing宣言なんてコンパイラが名前を探すためだけにあるのだから,置き換える必要すらありません。

Math

Re: WPFとデータバインディング

#24

投稿記事 by Math » 7年前

>置き換わらないし,そもそもC#のusing宣言なんてコンパイラが名前を探すためだけにあるのだから,置き換える必要すらありません。
この部分については気になっていたので今回http://dixq.net/forum/viewtopic.php?f=3&t=18870のNo.23で説明をすることができました。
MSDNhttps://msdn.microsoft.com/ja-jp/librar ... .110).aspxなど沢山の解説がありますが難解で具体例がなく説明不能だったのですがこれであきらかだと思われます。
読まれるかたがくれぐれも誤解なさらないようご注意くださいませ!

Math

Re: WPFとデータバインディング

#25

投稿記事 by Math » 7年前

ここhttp://www.atmarkit.co.jp/ait/articles/ ... ws097.htmlを詳しくよみ誤解なさらぬよう。”実行”して見ることが一番理解が出来ますよ。

sleep

Re: WPFとデータバインディング

#26

投稿記事 by sleep » 7年前

Visual Studio 2015 に付随するMSBuildを使用して作成されたbamlをexe実行時に読み込んだ際どのように展開されいるのかを確認するためのコードは以下です。

コード:

using System;
using System.IO;
using System.Reflection;

using System.Windows;

namespace ConsoleApplication1
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            var projectPath = $@"{Environment.ExpandEnvironmentVariables(@"%USERPROFILE%")}\Documents\visual studio 2015\Projects\C#\WpfApplication1";
            var assembly = Assembly.LoadFile($@"{projectPath}\WpfApplication1\bin\Debug\WpfApplication1.exe");

            using (var stream = new FileStream($@"{projectPath}\WpfApplication1\obj\Debug\MainWindow.baml", FileMode.Open))
            using (var reader = new System.Windows.Baml2006.Baml2006Reader(stream, new System.Xaml.XamlReaderSettings { LocalAssembly = assembly }))
            {
                while (reader.Read())
                {
                    Console.WriteLine("----------------------------------------");
                    Console.WriteLine($"NodeType: {reader.NodeType}");
                    Console.WriteLine($"Member: {reader.Member}");
                    Console.WriteLine($"Namespace: {reader.Namespace?.Namespace}");
                    Console.WriteLine($"SchemaContext: {reader.SchemaContext}");
                    //foreach (var name in reader.SchemaContext.GetAllXamlNamespaces())
                    //    foreach (var type in reader.SchemaContext.GetAllXamlTypes(name))
                    //    {
                    //        if (type.ContentProperty == null) continue;
                    //        Console.WriteLine(type.ContentProperty);
                    //        break;
                    //    }
                    Console.WriteLine($"Type: {reader.Type}");
                    Console.WriteLine($"Value: {reader.Value}");
                }
            }

            Console.ReadKey();
        }
    }
}

コード:

<Window.Resources>
    <local:ColorConverter x:Key="colorConverter"/>
</Window.Resources>

----------------------------------------
NodeType: StartMember
Member: System.Windows.FrameworkElement.Resources
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------
	NodeType: GetObject
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type:
	Value:
	----------------------------------------
		NodeType: StartMember
		Member: System.Windows.ResourceDictionary.DeferrableContent
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
		----------------------------------------
			NodeType: Value
			Member:
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value: System.IO.MemoryStream
		----------------------------------------
		NodeType: EndMember
		Member:
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
	----------------------------------------
	NodeType: EndObject
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type:
	Value:
----------------------------------------
NodeType: EndMember
Member:
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------

コード:

<Window.Resources>
    <ResourceDictionary>
        <local:ColorConverter x:Key="colorConverter"/>
    </ResourceDictionary>
</Window.Resources>

----------------------------------------
NodeType: StartMember
Member: System.Windows.FrameworkElement.Resources
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------
	NodeType: StartObject
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type: System.Windows.ResourceDictionary
	Value:
	----------------------------------------
		NodeType: StartMember
		Member: System.Windows.ResourceDictionary.DeferrableContent
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
		----------------------------------------
			NodeType: Value
			Member:
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value: System.IO.MemoryStream
		----------------------------------------
		NodeType: EndMember
		Member:
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
	----------------------------------------
	NodeType: EndObject
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type:
	Value:
----------------------------------------
NodeType: EndMember
Member:
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------

コード:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>
                <local:ColorConverter x:Key="colorConverter"/>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

----------------------------------------
NodeType: StartMember
Member: System.Windows.FrameworkElement.Resources
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------
	NodeType: StartObject
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type: System.Windows.ResourceDictionary
	Value:
	----------------------------------------
		NodeType: StartMember
		Member: System.Windows.ResourceDictionary.MergedDictionaries
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
		----------------------------------------
			NodeType: GetObject
			Member:
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value:
			----------------------------------------
				NodeType: StartMember
				Member: {http://schemas.microsoft.com/winfx/2006/xaml}_Items
				Namespace:
				SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
				Type:
				Value:
				----------------------------------------
					NodeType: StartObject
					Member:
					Namespace:
					SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
					Type: System.Windows.ResourceDictionary
					Value:
					----------------------------------------
						NodeType: StartMember
						Member: {http://schemas.microsoft.com/winfx/2006/xaml}_Items
						Namespace:
						SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
						Type:
						Value:
						----------------------------------------
							NodeType: StartObject
							Member:
							Namespace:
							SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
							Type: WpfApplication1.ColorConverter
							Value:
							----------------------------------------
								NodeType: StartMember
								Member: {http://schemas.microsoft.com/winfx/2006/xaml}Key
								Namespace:
								SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
								Type:
								Value:
								----------------------------------------
									NodeType: Value
									Member:
									Namespace:
									SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
									Type:
									Value: colorConverter
								----------------------------------------
								NodeType: EndMember
								Member:
								Namespace:
								SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
								Type:
								Value:
							----------------------------------------
							NodeType: EndObject
							Member:
							Namespace:
							SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
							Type:
							Value:
						----------------------------------------
						NodeType: EndMember
						Member:
						Namespace:
						SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
						Type:
						Value:
					----------------------------------------
					NodeType: EndObject
					Member:
					Namespace:
					SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
					Type:
					Value:
				----------------------------------------
				NodeType: EndMember
				Member:
				Namespace:
				SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
				Type:
				Value:
			----------------------------------------
			NodeType: EndObject
			Member:
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value:
		----------------------------------------
		NodeType: EndMember
		Member:
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
	----------------------------------------
	NodeType: EndObject
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type:
	Value:
----------------------------------------
NodeType: EndMember
Member:
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------

コード:

<Ellipse>
    <Ellipse.Fill>
        <Binding Path="Switching">
            <Binding.Converter>
                <local:ColorConverter/>
            </Binding.Converter>
        </Binding>
    </Ellipse.Fill>
</Ellipse>

----------------------------------------
NodeType: StartObject
Member:
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type: System.Windows.Shapes.Ellipse
Value:
----------------------------------------
	NodeType: StartMember
	Member: System.Windows.Shapes.Shape.Fill
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type:
	Value:
	----------------------------------------
		NodeType: StartObject
		Member:
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type: System.Windows.Data.Binding
		Value:
		----------------------------------------
			NodeType: StartMember
			Member: System.Windows.Data.Binding.Path
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value:
			----------------------------------------
				NodeType: Value
				Member:
				Namespace:
				SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
				Type:
				Value: System.Windows.Baml2006.TypeConverterMarkupExtension
			----------------------------------------
			NodeType: EndMember
			Member:
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value:
			----------------------------------------
			NodeType: StartMember
			Member: System.Windows.Data.Binding.Converter
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value:
			----------------------------------------
				NodeType: StartObject
				Member:
				Namespace:
				SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
				Type: WpfApplication1.ColorConverter
				Value:
				----------------------------------------
				NodeType: EndObject
				Member:
				Namespace:
				SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
				Type:
				Value:
			----------------------------------------
			NodeType: EndMember
			Member:
			Namespace:
			SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
			Type:
			Value:
		----------------------------------------
		NodeType: EndObject
		Member:
		Namespace:
		SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
		Type:
		Value:
	----------------------------------------
	NodeType: EndMember
	Member:
	Namespace:
	SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
	Type:
	Value:
----------------------------------------
NodeType: EndObject
Member:
Namespace:
SchemaContext: System.Windows.Baml2006.Baml2006SchemaContext
Type:
Value:
----------------------------------------

System.Windows.Baml2006.Baml2006SchemaContext とは
----------------------------------------
http://schemas.microsoft.com/winfx/2006 ... esentation
http://schemas.microsoft.com/xps/2005/0 ... tstructure
http://schemas.microsoft.com/xps/2005/06
http://schemas.microsoft.com/winfx/2006/xaml
http://schemas.microsoft.com/netfx/2009 ... esentation
http://schemas.microsoft.com/winfx/2006 ... osite-font
http://schemas.microsoft.com/netfx/2007 ... esentation

上記のような各スキーマで定義されているXamlで使用される型やらContentPropertyやらの情報が大量に格納されている
----------------------------------------


System.Windows.ResourceDictionary.DeferrableContent とは
-----------------------------------------------
Reference Sourceで確認するとコメントで記載されていますが

This should only be called in the deferred BAML loading scenario.
We cache all the data that we need away and then get rid of the actual object.
No one needs to actually get this property so we're returning null.
This property has to be public since the XAML parser cannot set this internal property in this scenario.

これは遅延BAMLロードシナリオでのみ呼び出されるべきです。
必要なすべてのデータをキャッシュし、実際のオブジェクトを取り除きます。
誰も実際にこのプロパティを取得する必要はありませんので、nullを返します。
このシナリオでは、XAMLパーサーはこの内部プロパティを設定できないため、このプロパティはパブリックである必要があります。
-----------------------------------------------


System.Windows.Markup.XamlReader.Load を使用してbamlを読み込んだ際、DeferrableContentが使用されていることを確認するためのコードは以下です。
オフトピック
Embed Resource (WpfApplication1.g.resources) として MainWindow.baml をアセンブリに埋め込まれた状態で、System.Windows.Markup.XamlReader.Load(System.Windows.Baml2006.Baml2006Reader)で再度 MainWindow.baml を読み込んだ場合、以下のエラーが出ます。

コード:

using System;
using System.IO;
using System.Reflection;

using System.Windows;

namespace ConsoleApplication1
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            var projectPath = $@"{Environment.ExpandEnvironmentVariables(@"%USERPROFILE%")}\Documents\visual studio 2015\Projects\C#\WpfApplication1";
            var assembly = Assembly.LoadFile($@"{projectPath}\WpfApplication1\bin\Debug\WpfApplication1.exe");

            using (var stream = new FileStream($@"{projectPath}\WpfApplication1\obj\Debug\MainWindow.baml", FileMode.Open))
            using (var reader = new System.Windows.Baml2006.Baml2006Reader(stream, new System.Xaml.XamlReaderSettings { LocalAssembly = assembly }))
            {
                //エラーが発生する箇所
                var window = System.Windows.Markup.XamlReader.Load(reader) as Window;
                Console.WriteLine(window.Resources["colorConverter"].GetType());
                new Application().Run(window);
            }
        }
    }
}

コード:

System.Windows.Markup.XamlParseException が発生しました。
  HResult=-2146233087
  LineNumber=11
  LinePosition=6
  Message='プロパティ 'System.Windows.ResourceDictionary.DeferrableContent' の Set で例外がスローされました。' 行番号 '11'、行位置 '6'。
  Source=PresentationFramework
  StackTrace:
       場所 System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       場所 System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, Boolean skipJournaledProperties, Uri baseUri)
       場所 System.Windows.Markup.XamlReader.Load(XamlReader xamlReader, ParserContext parserContext)
       場所 System.Windows.Markup.XamlReader.Load(XamlReader reader)
       場所 ConsoleApplication1.Program.Main(String[] args) 場所 C:\Users\Griff\documents\visual studio 2015\Projects\C#\ConsoleApplication1\ConsoleApplication1\Program.cs:行 33
  InnerException:
       HResult=-2147024809
       Message=項目は既に追加されています。辞書のキー: 'colorConverter'  追加されるキー:'colorConverter'
       Source=mscorlib
       StackTrace:
            場所 System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
            場所 System.Collections.Hashtable.Add(Object key, Object value)
            場所 System.Windows.ResourceDictionary.SetKeys(IList`1 keyCollection, IServiceProvider serviceProvider)
            場所 System.Windows.ResourceDictionary.SetDeferrableContent(DeferrableContent deferrableContent)
            場所 System.Windows.Baml2006.WpfSharedBamlSchemaContext.<>c.<Create_BamlProperty_ResourceDictionary_DeferrableContent>b__297_0(Object target, Object value)
            場所 System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
            場所 MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
            場所 MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
       InnerException:

sleep

Re: WPFとデータバインディング

#27

投稿記事 by sleep » 7年前

Math さんが書きました:>置き換わらないし,そもそもC#のusing宣言なんてコンパイラが名前を探すためだけにあるのだから,置き換える必要すらありません。
この部分については気になっていたので今回http://dixq.net/forum/viewtopic.php?f=3&t=18870のNo.23で説明をすることができました。
MSDNhttps://msdn.microsoft.com/ja-jp/librar ... .110).aspxなど沢山の解説がありますが難解で具体例がなく説明不能だったのですがこれであきらかだと思われます。
読まれるかたがくれぐれも誤解なさらないようご注意くださいませ!
一応、注記しておきますが、

xamlをコンパイルすると、2つのファイルができます。
bamlファイルとcsファイルです。
csファイルには、partialでクラスが定義されており、Application.LoadComponentでbamlを読み込むコードと主にxaml上でx:Nameまたはイベントの定義があった場合に対応するコードが追記されます。
このcsファイルに using で宣言されているのは、このファイル内で有効な名前空間のみであって、xamlのスキーマ宣言とは全く関係ありません。

Math

Re: WPFとデータバインディング

#28

投稿記事 by Math » 7年前

ここhttp://www.atmarkit.co.jp/ait/articles/ ... ws105.htmlでよく知ってますよ。
partialもFormの頃からのことで当然だし私はFormプログラムもxamlをつかいますよ。
bamlを調べるまでもなくexeをツールでみれば全VBソースが得られます。
http://csi.nisinippon.com/baml.png

(細かくは私の勘違いかもしれません。言わんとしてるのはhttp:以下が名前空間の指定であるとMSDNにある事です。MSDNにあるMSDNの膨大な資料から”資料”の出所を調べて見つけたらここに記します。ただMSDNは汎用的にかかれていて(あっちこっち参照せよとかいてあるので)わかりにくく他の資料で見た覚えがあります..一度時間のあるときFormとWPFでの違いも含め整理したいと思っていますので。)

sleep

Re: WPFとデータバインディング

#29

投稿記事 by sleep » 7年前

Math さんが書きました:(細かくは私の勘違いかもしれません。言わんとしてるのはhttp:以下が名前空間の指定であるとMSDNにある事です。MSDNにあるMSDNの膨大な資料から”資料”の出所を調べて見つけたらここに記します。ただMSDNは汎用的にかかれていて(あっちこっち参照せよとかいてあるので)わかりにくく他の資料で見た覚えがあります..一度時間のあるときFormとWPFでの違いも含め整理したいと思っていますので。)
そのような情報は私に対してであれば不要です。提示していただく必要はありません。
とりあえず、質問者はそのようなことを聞く質問はされてないので、個人的な調査およびその結果の報告は不要です。

もし、スキーマがどのように定義されているのかを知りたいのであれば、XmlnsDefinitionAttribute を調べてみてください。

JIBA

Re: WPFとデータバインディング

#30

投稿記事 by JIBA » 7年前

皆様の研究能力に非常に感心しております。
本当に勉強になりました。

閉鎖

“C言語何でも質問掲示板” へ戻る