DataContextについて

このQ&Aのポイント
  • Visual C# 2010 Expressを使用して、DataContextに関する問題が発生しました。
  • FooクラスのメンバAuthorizedを使用してUserControl1とUserControl2を切り替えるためのコードを実装しましたが、うまく動作しません。
  • Datacontextとは、データバインディングにおいてデータのソースを指定するためのプロパティです。この記事ではDataContextについて詳しく解説します。
回答を見る
  • ベストアンサー

DataContextについて

visual C# 2010 Express を使用しています。 UserControl1とUserControl2をFooクラスのメンバAuthorizedによって 切り替えるということをしたいと思い、 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" Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication1"> <Window.DataContext> <my:Foo/> </Window.DataContext> <Grid> <my:UserControl1 HorizontalAlignment="Left" Margin="140,74,0,0" x:Name="userControl11" VerticalAlignment="Top" Height="44" Width="82" Visibility="{Binding Path=NotAuthorized, Converter={StaticResource BooleanToVisibilityConverter1}}" /> <my:UserControl2 Height="45" HorizontalAlignment="Left" Margin="288,65,0,0" x:Name="userControl21" VerticalAlignment="Top" Width="77" Visibility="{Binding Path=Authorized, Converter={StaticResource BooleanToVisibilityConverter1}}" /> <Button Content="Button" Height="38" HorizontalAlignment="Left" Margin="38,109,0,0" Name="button1" VerticalAlignment="Top" Width="80" Click="button1_Click" /> <TextBox Height="40" HorizontalAlignment="Left" Margin="46,34,0,0" Name="textBox1" VerticalAlignment="Top" Width="88" /> </Grid> </Window> そしてFooクラス [Foo.cs] class Foo { private bool _authorized = false; public bool Authorized { get { return _authorized; } set { _authorized = value; } } public bool NotAuthorized { get { return !Authorized; } } } そして、MainWindow.xaml.csのbutton1_Click内で、 Foo f = new Foo(); f.Authorized = true; とやったのですが、切り替わらないのです。 なんとなく自分でもこれだけでは切り替わらないだろうなと想像はつくのですが、 でも下の図のプロパティでは [ソース: (Datacontext - Foo)] とありDatacontextはFooクラスだと認識してますよね? なのでこの記述 Visibility="{Binding Path=NotAuthorized, Converter={StaticResource BooleanToVisibilityConverter1}}" だけでも認識してくれるのかなと期待したのですが、駄目でした・・・ この場合はどう記述すれば良いのでしょうか?またなぜそれが必要なのかという理由も教えて頂けないでしょうか?

質問者が選んだベストアンサー

  • ベストアンサー
回答No.3

> なるほど、Fooクラスというのはアプリケーションの全体のモデルということですか。 > ですが、その概念が分からなかったというか、今でもあまりイメージできないのですが、 > というのも、今まで自分はPHP言語のフレームワークを利用してなにかと作業(かじった程度ですが^^;))していたのですが、 了解です。 こう言ってはなんですが,WPFで作る時にはPHPのMVCに対する考え方を一端忘れてしまってもかまわないと思います。 PHPのフレームワーク自体には明るくないのですが,WebアプリケーションにおけるMVCについては一応は知っているつもりです。 で,MVCに関しては, ・元々Smalltalkでの開発時に生まれた →今で言うデスクトップアプリケーションに相当するもので使われるもの ・Webの世界でMVCという名前が流用されて,こちらが有名になった →Modelに関して大きな誤解ができる余地ができた ・MVCをWPFやSilverlightに適用しようとした場合に,MVVMというパターンがWPF等に都合が良いように作られた →私がModelやViewModelと言っているのは,MVVMにおけるもの という状況だと考えてください。 デスクトップアプリケーションでは,Modelが状態を保持します (Modelは「ステートフル」)。 つまり,例えばログインした後のユーザー名やログイントークン,入力中のテキストなどをModelが保持し続けます。 また,それが可能です。 それに対して,同様のことをWebアプリケーションで行う場合,HTTPというプロトコルの特性上,リクエスト-レスポンスでModelは原則的に消滅します (Modelは「ステートレス」)。 このため,「アプリケーション全体」という考え方が存在しません。 呼び出しごとにアプリケーション全体の情報を用意して,必要な部分だけ使う,というのは無意味ですから。 データベースサーバーにシリアライズされたデータを,必要な部分だけデシリアライズして使うことになります。 > MVCといえば、Model、View、Controller、に分けて、その名の通り > データ関係はModel > 表示関係はView > 制御関係はController > が担当して、コントローラ内でモデルを呼び出し処理をさせて > コントローラ内でviewに変数をアサイン(?)する。その変数を参照してviewで表示。 オリジナルのMVCでは,入力をCが受け付け,Mを呼び出します。 VはMの変更を「監視し」,Mの変更があるとV自身を修正します。 # ツールキットの都合上,Vが入力を受け付けてCに通知し,という形にならざるを得ないこともありますが。 「監視し」,という点が重要で,サーバー側でMVCが完結するWebアプリケーションにおいては,監視ができないため,歪なMVCになってしまっています。 オリジナルはMがステートフルなのです。 将来的にHTML5やその後継が普及した場合,JavaScriptでの記述が増え,jsによるMVC or 相当品が出てくるでしょう。 その場合,Mはおそらくステートフルになると思います。 # ロジックはサーバーに投げるとしても,元データはMが保持し続ける。 > そのケースにおいて今回のFooクラスというかアプリケーション全体のモデルに相当する箇所は、 > PHPのフレームワークの場合ではどのあたりなのでしょうか? WebアプリケーションのMVCというでは存在しませんし,存在するだけ無駄になります。 ステートフルModelであるクライアントアプリケーションと,ステートレスModelであるWeb (HTTP) アプリケーションの違いの部分でもあります。 references) 日本のMVVMに関する第一人者といってもよい,MVVMライブラリであるLivetの作者でもある尾上氏のBlog Blog: MVVMパターンとイベント駆動開発、そしてMVC/MVP/PMパターンとの関係 – 何故MVVMなのか - the sea of fertility http://ugaya40.net/wpf/mvvm-mvc-mvp-pm-eventdriven.html Blog: MVVMパターンの適応 – 2011年のMVVMパターンの常識 - the sea of fertility http://ugaya40.net/mvvm/mvvm-2011.html > それと、あれからいくつか試してみたのですが、コード側で > Binding binding = new Binding("NotAuthorized"); > binding.Converter = new BooleanToVisibilityConverter(); > this.userControl11.SetBinding(UserControl.VisibilityProperty, binding); > this.DataContext = this.f; > とやったらできました。 > xamlはあまり分からないので^^;)、コード側で記述できると安心するというか。。。 XAMLの記述はほぼコードに直すことができます。 たとえば, <Window.DataCotnext> <local:Foo /> </Window.DataContext> は, this.DataContext = new Foo(); に相当します。 属性の設定は,プロパティへの代入という形でだいたい処理できます。 ただし,DataTemplateなどを考えると,コードだけに頼るのはWPFの強みを消している気がします。 なお,XAMLで書いた物は,objディレクトリの中に.g.csのような形でC#コード化されているはずです。 > とくにBooleanToVisibilityConverterというかそこらへんに絞ると圧倒的に情報が少なくなりますよね。。 単純なBindingの話ならそれなりに見つかりますが,確かにConverterは少なくなりますね。 Converterが必要な状況というのはそれほど多くない上,VMである程度制御できてしまうので。 MSDNあさるのが一番色々載っているかもしれません。 > あと、これも教えて頂きたいのですが、 > <local:Foo/> > とのことなのですが、それだと自分の環境(たぶん初期の状態)では > 「'local' は宣言されていないプレフィックスです。」 > とエラーが出てしまいます・・・ > なので自分は > <my:Foo/> > にしてやっているのですが、どうすればlocalでできるようになるのでしょうか? myでもいいですよ。 私自身が,自身の慣例としてlocalをXML名前空間に使っているだけですので。 XAMLではなく,XMLの世界の話ですが,XML名前空間というものがあります。 例えばXHTMLとMathMLを混合させて使うような場合に,同じ要素名を分けて使うための物ですが, その機構で定義されるのがlocalでありmyです。 Windowの開始タグに,xmlns:my="clr-namespace:(コードの名前空間名)"という属性がありませんか。 これがXML名前空間の宣言です。 xmlns="(名前空間URI)"だと,プリフィックス無しのタグの名前空間の宣言, xmlns:(プリフィックス)="(名前空間URI)"だと,プリフィックスで指定したタグや属性の名前空間の宣言になります。 XML名前空間はURI (≒URL) を使って宣言する (XHTMLだとhttp://www.w3.org/1999/xhtml ) のですが, XAMLでは,スキームとしてclr-namespaceを指定することで,コードの名前空間を指定できます。 MSDN: XAML 名前空間および WPF XAML の名前空間の割り当て # アセンブリ内の XML 名前空間への CLR 名前空間の割り当て http://msdn.microsoft.com/ja-jp/library/ms747086.aspx#Mapping_CLR_Namespaces_to_XML_Namespaces_in_an

takagoo100
質問者

お礼

ご回答ありがとうございます。 なるほど、とても参考になりました。 なんといって良いのか分かりませんが、一度に多くの情報を得たので、 まだ整理しきれてませんが、ここのサイト(http://ugaya40.net/mvvm/mvvm-2011.html) も含めて、一通り読んだだけですけどとても興味ある情報があったので、 これから時間のあるときにじっくり読んで考えてみたいと思います。 それと、仰るとおりlocalに変更してできました。 ありがとうございます。

その他の回答 (2)

回答No.2

> と変更してみたのですがPropertyChangedがnullなので > 当然のことながら入ってこないのです。。 > どこでPropertyChangedを生成というかnullじゃない状態に > するのでしょうか? えーっと,バインドするオブジェクト自体は,WindowなりControlなりのDataContextに指定します。 コードなら, public partial class MainWindow : Window { private Foo _foo; public MainWindow() { InitializeComponent(); _foo = new Foo(); DataContext = _foo; } private void button1_Click(object sender, RoutedEventArgs e) { _foo.Authorized = true; } } という感じになります。 また,XAMLでは <Window.DataContext> <local:Foo/> <!-- localはFooの名前空間に対してつけたxmlのプリフィックス。Windowの属性として,xmlns:local="clr-namespace:WpfApplication1"のように定義 --> </Window.DataContext> と書けば,自動でオブジェクトを作ってバインドしてくれます。コードビハインドは, public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { ((Foo)DataContext).Authorized = true; } } となります。 キャストが邪魔に思えるかもしれませんが,最終的にbutton1_ClickすらFooクラス内に記述してバインドで処理できるようになるので (Q7064034のANo.3,RelayCommandとLoginプロパティ等を参照), このClickイベントが削除されるまでの一時的なものです。 > それとUserControl1に > DataContext="{Binding ModelForUserControl1}" > は追加しないと駄目なのでしょうか? > そもそもFooクラスとModelForUserControl1の関係が > いまいち理解できないというか、、 > ModelForUserControl1をnewするときにFooクラス自身を渡していますが、 > これも > DataContext="{Binding ModelForUserControl1}" > この存在を理解しないとたぶんイメージできないと思うので > 申し訳ないのですが、そのあたりの解説もお願いできないでしょうか? MVVMという物を念頭に置いているのですが,最終目標はViewとLogicの分離です。 ただ,今回の作りはMVVMのMとVMを(意図的に)分離していません。 そのため,Logicを含むModelがViewに引きずられています。 まず,Fooという名前をつけてしまいましたが,これはアプリケーション全体のModelに相当します。 # MainViewModelとかの方がよかったですね。 で,UserControl1についてもViewとLogicを分離すれば当然Logic部分に相当する,Modelが出てきます。 これがUserControl1ViewModelクラスです。 で,このModelは,Fooの特定のインスタンスから生成されるのが自然です。 # アプリケーション全体の一部分なので。 そのため,FooクラスがUserControl1ViewModelクラスを生成します。 その生成したインスタンスをUserControl1に教えてあげる必要があります。 そのために,ModelForUserControl1というプロパティを用意して外部から取得できるようにして, UserControl1のDataContextにバインドする形で「自分自身に紐付いたFooクラスのインスタンスに紐付いたUserControl1ViewModelクラスのインスタンス」を「自分自身の子コントロールであるUserControl」に引き渡しています。 UserControl1ViewModelクラスの作成時にFooクラスのインスタンスを渡しているのは,単純に楽になるから,という程度の物です。 必要なければ渡す必要はありません。 # 例示したものでは,UserControl1ViewModelクラス中で認証処理を行って,結果をFoo側に渡す必要があったためFooを渡していました。 画像を添付しますので,クラス同士の関係について,ある程度イメージが掴めて頂けるとうれしいです。 元画像: http://pub.idisk-just.com/fview/uG65y08xEVsl4AXcqSzKSeXtVZ6OAfFFcYt9Zr0tkm9-j2tyyyyHI3inOYvmrqa0ZUudo-VT8VQwG84_AMmDDr76NwNTU4kw.png データバインディング関係の記事では,C#関連の記事が色々あって有名な Site: ++C++;// 未確認飛行 C http://ufcpp.net/ の管理人である岩永さんの@ITにおける記事 Site: WPF入門 - @IT http://www.atmarkit.co.jp/fdotnet/chushin/introwpf_index/ の第5回,第6回などが役に立つと思います。

takagoo100
質問者

お礼

ご回答ありがとうございます。 画像まで提示して頂きありがとうございます。 なるほど、Fooクラスというのはアプリケーションの全体のモデルということですか。 ですが、その概念が分からなかったというか、今でもあまりイメージできないのですが、 というのも、今まで自分はPHP言語のフレームワークを利用してなにかと作業(かじった程度ですが^^;))していたのですが、 MVCといえば、Model、View、Controller、に分けて、その名の通り データ関係はModel 表示関係はView 制御関係はController が担当して、コントローラ内でモデルを呼び出し処理をさせて コントローラ内でviewに変数をアサイン(?)する。その変数を参照してviewで表示。 という流れだと思います。 そこでモデルなのですが、例えばUserモデル(id,username,password)とArticleモデル(id,body,author) があったとします。そのケースにおいて今回のFooクラスというかアプリケーション全体のモデルに相当する箇所は、 PHPのフレームワークの場合ではどのあたりなのでしょうか? PHPのフレームワークの場合で全体をまとめるモデルというのがピンとこないというか、イメージできないのです・・・ Yune-KichiさんがPHPのフレームワークについてどれくらいご存知か分からないのですが、 もしご存知でしたら、その2つを比べることによってイメージできればと思いまして。 それと、あれからいくつか試してみたのですが、コード側で Binding binding = new Binding("NotAuthorized"); binding.Converter = new BooleanToVisibilityConverter(); this.userControl11.SetBinding(UserControl.VisibilityProperty, binding); this.DataContext = this.f; とやったらできました。 xamlはあまり分からないので^^;)、コード側で記述できると安心するというか。。。 ただこれひとつネットなどで探すにしても苦労しました・・・ とくにBooleanToVisibilityConverterというかそこらへんに絞ると圧倒的に情報が少なくなりますよね。。 あと、これも教えて頂きたいのですが、 <local:Foo/> とのことなのですが、それだと自分の環境(たぶん初期の状態)では 「'local' は宣言されていないプレフィックスです。」 とエラーが出てしまいます・・・ なので自分は <my:Foo/> にしてやっているのですが、どうすればlocalでできるようになるのでしょうか?

回答No.1

Q7064034で回答した者です。 WinForms/WPF/Silverlightすべてのデータバインドで双方向のバインドを行うには, System.ComponentModel.INotifyPropertyChangedインターフェースを実装したクラスを利用する必要があります。 # .NET 1.xではプロパティごとに(PropertyName)Changedというイベントを用意するのですが。 そして,プロパティの値が変更されたタイミングで,PropertyChangedイベントを発生させる必要があります。 プロパティの値が変わったことを知る方法は毎回取得する以外に存在しませんが, PropertyChangedイベントによって,UI側はバインドされているプロパティの値が変更されたことを知ります。 同じように,コレクションをバインドした場合,INotifyCollectionChangedというインターフェースがあります。 特定の要素の位置が変更したとか,追加されたとかを通知するインターフェースです。 # 実装クラスであるObservableCollection<T>があるので,あまり使うことはありませんが。 Q7064034の回答2のコード,AuthorizaedのSet部分に, if (PropertyChanged != null) { PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Authorized")); PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("NotAuthorized")); } とあるのは,変更を通知する為です。 NotAuthorizedはAuthorizedに連動させているため,Authorizedの設定時にプロパティの変更を通知しています。 references) MSDN: INotifyPropertyChanged インターフェイス (System.ComponentModel) http://msdn.microsoft.com/ja-jp/library/system.componentmodel.inotifypropertychanged.aspx MSDN: データ バインド (WPF) http://msdn.microsoft.com/ja-jp/library/ms750612.aspx MSDN: データ バインディングの概要 http://msdn.microsoft.com/ja-jp/library/ms752347.aspx MSDN: バインディング ソースの概要 http://msdn.microsoft.com/ja-jp/library/ms743643.aspx MSDN: 方法 : プロパティの変更通知を実装する http://msdn.microsoft.com/ja-jp/library/ms743695.aspx

takagoo100
質問者

お礼

ご回答ありがとうございます。 その節はありがとうございました。 すいません、せっかくコードを提示して頂いて本当ならその場で 疑問を解決するのがベストなんでしょうけど、なかなか自分の理解力だと 1つづ疑問を片付けていかないと理解できないので^^;)申し訳ないのです。。 仰るとおり、FooクラスにAuthorizedにPropertyChangedを追加して そしてSystem.ComponentModel.INotifyPropertyChangedも継承して class Foo : System.ComponentModel.INotifyPropertyChanged { private bool _authorized = false; public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public bool Authorized { get { return _authorized; } set { _authorized = value; if (PropertyChanged != null) { MessageBox.Show("in"); PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Authorized")); PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("NotAuthorized")); } } } public bool NotAuthorized { get { return !Authorized; } } } MainWindow.xam.csは public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Foo f = new Foo(); f.Authorized = true; } } と変更してみたのですがPropertyChangedがnullなので 当然のことながら入ってこないのです。。 どこでPropertyChangedを生成というかnullじゃない状態に するのでしょうか? それとVisibilityに DataContext="{Binding ModelForUserControl1}" は追加しないと駄目なのでしょうか? そもそもFooクラスとModelForUserControl1の関係が いまいち理解できないというか、、 ModelForUserControl1をnewするときにFooクラス自身を渡していますが、 これも DataContext="{Binding ModelForUserControl1}" この存在を理解しないとたぶんイメージできないと思うので 申し訳ないのですが、そのあたりの解説もお願いできないでしょうか?

takagoo100
質問者

補足

すいません、訂正です。 >それとVisibilityに ではなくて それとUserControl1に

関連するQ&A

  • wpf datagrid メモリリーク

    wpfのdatagridを利用してデータ表示しております。 1レコードを多段構成で表示するため、ユーザーコントロールにdatagridを配置し、グリッド内に各コントロールを配置する方法で実現しております。 チェックボックスも配置しており、スクロール時に初期化される現象が発生したため、仮想化をOFFにしております。 少ないデータ件数であれば問題ないのですが、大量データ(3500件程度)の場合には メモリリークしてしまいます。 DataGridにチェックボックスを配置した場合の実装で、上記の事象を 改善する方法をご存知の方がいらっしゃいましたらご教授頂けると幸いです。 以下2つが実装しているxamlとなります。 ★Grid_Tab_Roke_Main  ユーザーコントロールにDataGridを配置したものとして実装しています。 <UserControl x:Class="Grid_Tab_Roke_Main" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:_XX_WPF商品管理" mc:Ignorable="d" d:DesignHeight="200.373" d:DesignWidth="300" Height="Auto" Width="Auto"> <DataGrid ItemsSource="{Binding}" VirtualizingStackPanel.IsVirtualizing="False" VirtualizingStackPanel.VirtualizationMode="Standard" EnableColumnVirtualization="False" EnableRowVirtualization="False" ScrollViewer.CanContentScroll="True" ScrollViewer.IsDeferredScrollingEnabled="True" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" HeadersVisibility="None" Margin="0,0,0,0"> <DataGrid.Columns> <DataGridTemplateColumn > <DataGridTemplateColumn.CellTemplate> <DataTemplate> <local:Grid_Tab_Roke_Detail /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </UserControl> ★Grid_Tab_Roke_Detail グリッド内にコントロールを配置しており、データテーブルよりバインドしています。項目は全て数点を抜粋して記載しております。 <UserControl x:Class="Grid_Tab_Roke_Detail" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Height="70" Width="1227" Background="White" Loaded="UserControl_Loaded"> <Grid> <TextBox x:Name="Text_Roke" Text="{Binding ロケーション名, Mode=OneTime, StringFormat=\{0:N0\}}" HorizontalAlignment="Left" Height="21" Margin="56,22,0,27" TextWrapping="Wrap" VerticalAlignment="Center" Width="181" RenderTransformOrigin="0.406,0.026" Background="{x:Null}" FontFamily="Arial" VerticalContentAlignment="Center" FontWeight="Bold" MaxWidth="200" MinHeight="16" IsHitTestVisible="True" FontSize="16" Foreground="Black"/> <TextBox x:Name="Text_HinCD" Text="{Binding 商品コード, Mode=OneTime, StringFormat=\{0:N0\}}" HorizontalAlignment="Left" Height="21" Margin="242,22,0,27" TextWrapping="Wrap" VerticalAlignment="Center" Width="62" RenderTransformOrigin="0.406,0.026" Background="{x:Null}" FontFamily="Arial" VerticalContentAlignment="Center" FontWeight="Bold" MaxWidth="150" MinHeight="16" IsHitTestVisible="True" FontSize="16" Foreground="Black"/> <CheckBox x:Name="Chk_Sentaku" Content="選択" IsChecked="{Binding IsSelected.Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="3,3,0,0" VerticalAlignment="Top" Width="48" Height="65" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" /> <TextBox x:Name="Text_HinNM" Text="{Binding 商品名, Mode=TwoWay, StringFormat=\{0:N0\}}" HorizontalAlignment="Left" Height="21" Margin="304,22,0,27" TextWrapping="Wrap" VerticalAlignment="Center" Width="330" RenderTransformOrigin="0.406,0.026" Background="{x:Null}" FontFamily="Arial" VerticalContentAlignment="Center" FontWeight="Bold" MaxWidth="350" MinHeight="16" IsHitTestVisible="True" FontSize="16" Foreground="Black"/> </Grid> </UserControl>

  • WPFのチェックボックス

    VisualBasic 2013 でWPFを利用してグリッドを作成しております。 ユーザーコントロールにDataGridを配置し、Grid内にチェックボックスを1つ 配置しています。 データ表示後は1レコードに1つチェックボックスが配置された状態と なります。 データ表示は問題なく行えるのですが、チェックボックスの動作が 想定と異なってしまいます。 ・現在チェックボックスの挙動  複数レコードでチェックボックスのチェックを付けた場合、  画面をスクロールするとチェックが消える。 このような現象が発生する原因と対策がお分かりの方がいらっしゃいましたら ご教授頂けると幸いです。 上記現象が発生するxamlは以下の通りです。 <UserControl x:Class="Grid_Tab_Roke_Detail" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Height="70" Width="1227" Background="White"> <UserControl.Resources> <!-- ラジオボタンの共通styleを指定 --> <!-- トグルボタン風に押すと色を変える --> <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type ToggleButton} }"> <Style.Triggers> <!-- 未チェック時は透明 --> <Trigger Property="IsChecked" Value="{x:Null}"> <Setter Property="Background" Value="Transparent" /> </Trigger> <Trigger Property="IsChecked" Value="False"> <Setter Property="Background" Value="Transparent" /> </Trigger> <!-- チェック時は青 --> <Trigger Property="IsChecked" Value="True"> <Setter Property="Background" Value="Blue"/> </Trigger> </Style.Triggers> </Style> </UserControl.Resources> <Grid> <CheckBox Content="選択" IsChecked="{Binding IsSelected.Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="3,3,0,0" VerticalAlignment="Top" Width="48" Height="57" /> <TextBox x:Name="Text_HinNM" Text="{Binding 商品名, Mode=OneTime, StringFormat=\{0:N0\}}" HorizontalAlignment="Left" Height="21" Margin="304,22,0,27" TextWrapping="Wrap" VerticalAlignment="Center" Width="330" RenderTransformOrigin="0.406,0.026" Background="{x:Null}" FontFamily="Arial" VerticalContentAlignment="Center" FontWeight="Bold" MaxWidth="350" MinHeight="16" IsHitTestVisible="True" FontSize="16"> <TextBox.Foreground> <SolidColorBrush Color="Black"/> </TextBox.Foreground> </TextBox> </Grid> </UserControl>

  • Visualbasic2010 WPF データ更新

    VisualBasic 2010 を利用してWindowsアプリケーションを行っております。 Form上にElementHostを配置し、データベースより抽出した結果をWPFで作成したグリッド(DataGrid)に表示しております。 以下の点について分る方がいらっしゃいましたらご教授頂けますと幸いです。 DataGridでデータを更新した場合にDataTableも更新したい ソースは以下の構成となります。 ★Item_Main.xaml <UserControl x:Name="UserControl1" x:Class="Item_Main" xmlns:local="clr-namespace:TEST" mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="300" Height="Auto" Width="Auto" GotFocus="UserControl_GotFocus"> <DataGrid x:Name="DataGrid_1" ItemsSource="{Binding}" ScrollViewer.CanContentScroll="True" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Standard" ScrollViewer.IsDeferredScrollingEnabled="True" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" HeadersVisibility="None" Margin="0,0,0,0"> <DataGrid.Columns> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <local:Item_Detail /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </UserControl> ★Item_Detail.xaml <UserControl x:Name="UserControl2" x:Class="Item_Detail" mc:Ignorable="d" d:DesignHeight="136" Width="1090" Loaded="UserControl_Loaded"> <UserControl.Background> <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.WindowColorKey}}"/> </UserControl.Background> <Grid Name="GP_Panel" KeyboardNavigation.TabNavigation="Local"> <Grid.ColumnDefinitions> <ColumnDefinition Width="69*"/> <ColumnDefinition Width="151*"/> </Grid.ColumnDefinitions> <TextBox x:Name="Text_Pre_CS" Text="{Binding 数量, Mode=TwoWay, TargetNullValue=0}" HorizontalAlignment="Left" Height="22" Margin="161,102,0,12" TextWrapping="Wrap" Width="60" Background="White" FontFamily="Arial" HorizontalContentAlignment="Right" VerticalContentAlignment="Center" FontWeight="Bold" Foreground="Black" Grid.Column="1" TabIndex="1" FontSize="15" /> </Grid> </UserControl> ★Item_Detail.xaml.vb  ※現在はデータ編集時に以下のように処理しております。 '/ 本画面のDataRowを取得 Dim dt_row As DataRow Dim dt_row_view As DataRowView dt_row_view = CType(Me.DataContext, DataRowView) dt_row = dt_row_view.Row   dt_row.Item("数量") = "0" DataRowはDataTableとは異なると認識しておりますので   現在のロジックではDataTable側は更新されない事は   理解しているのですが、Item_Detail.xaml.vbにて   DataTableの特定行数を取得する方法等が分らず   目的の動作が実現できていません。   大変お手数おかけ致しますが、   宜しくお願い致します。 以上です。   

  • VisualBasic 2010 WPFのData

    Visualbasic 2010を利用してWindows Formアプリケーションに WPFのDataGridを配置しております。 以下の2点の制御を行いたいと考えておりますが、 ご存知の方がいらっしゃればご教授頂けますと幸いです。 (1)フォームよりWPFのDataDrid内の値を編集した場合に  Dattableに反映したい  現在はフォーム側で以下のように参照しています。 Dim dt_row As DataRow Dim dt_row_view As DataRowView   dt_row_view = CType(Me.DataContext, DataRowView) dt_row = dt_row_view.Row (2)DataGridにTextBoxを2つ配置(数量1、数量2)しておりますが、  エンターキー押下時に数量1、数量2の順でカーソル遷移でき  ないでしょうか。  現在はエンターキーを押下すると次の行に遷移してしま  います。 以下にソースの抜粋を掲示致します。 ★Form1.vb (HostedContentName) Item_Main2 Me.Item_Main2.DataContext = dt   ※データテーブルにはDBからSELECTした結果をセットしています。 ★Item_Main.xaml <UserControl x:Name="UserControl1" x:Class="Item_Main" xmlns:local="clr-namespace:TESTアプリ" <DataGrid x:Name="DataGrid_1" ItemsSource="{Binding}" ScrollViewer.CanContentScroll="True" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Standard" ScrollViewer.IsDeferredScrollingEnabled="True" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" HeadersVisibility="None" Margin="0,0,0,0" KeyDown="DataGrid_KeyDown"> <DataGrid.Columns> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <local:Item_Detail /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </ ★Item_Detail.xaml.vb Private Sub Btn_Click(sender As Object, e As Windows.RoutedEventArgs) Handles Btn.Click Dim dt_row As DataRow Dim dt_row_view As DataRowView dim wk_1 as string '/ 本画面のDataRowを取得 dt_row_view = CType(Me.DataContext, DataRowView) dt_row = dt_row_view.Row '/ 画面で編集した値を変数にセット If COMMON.NullNothingChk(dt_row.Item("数量1")) = False Then wk_1 = dt_row.Item("数量1").ToString Else wk_1 = "0" End If '/ 画面で編集した内容をデータテーブルにセットしたい '/ 今のままではグリッドを再描画すると編集内容がクリアされてしまう End Sub ★Item_Detail.xaml <UserControl x:Name="UserControl2" x:Class="Item_Detail" mc:Ignorable="d" d:DesignHeight="136" Width="1090" Loaded="UserControl_Loaded"> <Grid Name="GP_Panel" KeyboardNavigation.TabNavigation="Local"> <Grid.ColumnDefinitions> <ColumnDefinition Width="69*"/> <ColumnDefinition Width="151*"/> </Grid.ColumnDefinitions> <TextBox x:Name="Text_ItemCd" Text="{Binding 商品コード}" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" Width="56" Background="{x:Null}" FontFamily="Arial" FontSize="14" VerticalContentAlignment="Center" FontWeight="Bold" IsHitTestVisible="True" Foreground="Black" Margin="4,23,0,93" HorizontalContentAlignment="Center" IsReadOnly="True" IsTabStop="False"/> <TextBox x:Name="Text_ItemNm" Text="{Binding 商品名}" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" Width="316" Background="{x:Null}" FontFamily="Arial" FontSize="16" VerticalContentAlignment="Center" IsHitTestVisible="True" Foreground="Black" Margin="62,23,0,93" BorderBrush="{x:Null}" Grid.ColumnSpan="2" IsReadOnly="True" IsTabStop="False"/> <TextBox x:Name="Text_1" Text="{Binding 数量1, Mode=TwoWay, TargetNullValue=0}" HorizontalAlignment="Left" Height="18" Margin="176,102,0,16" TextWrapping="Wrap" Width="60" Background="White" FontFamily="Arial" HorizontalContentAlignment="Right" VerticalContentAlignment="Center" FontWeight="Medium" Foreground="Black" Grid.Column="1" TabIndex="1" /> <TextBox x:Name="Text_2" Text="{Binding 数量2, Mode=TwoWay, TargetNullValue=0}" HorizontalAlignment="Left" Height="18" Margin="236,102,0,16" TextWrapping="Wrap" Width="60" Background="White" FontFamily="Arial" HorizontalContentAlignment="Right" VerticalContentAlignment="Center" FontWeight="Medium" Foreground="Black" Grid.Column="1" TabIndex="2" /> </Grid> </UserControl>

  • Equalsはどこから呼出してるのでしょうか?

    wpfの次のpublic override int GetHashCode()とpublic override bool Equals(object obj)とpublic override string ToString()にブレークポイントを設定し「開始」をすると起動時にEqualsで中断、コンボボックスをクリックするとToStringやGetHashCodeで中断しますが、これらの呼び出し元はどこなのでしょうか? 何卒、ご教授よろしくお願いします。 mainwindow.xaml <Grid> <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="200,138,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{x:Static local:classA.comblist}"/> </Grid> mainwindow.xaml.cs public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } class classA { public static classB[] comblist { get { classB[] List = new classB[3]; classB a1 = new classB(); a1.listb = "AAA"; List[0] = a1; classB a2 = new classB(); a2.listb = "BBB"; List[1] = a2; classB a3 = new classB(); a3.listb = "CCC"; List[2] = a3; return List; } } } class classB { private string _listb; public string listb { get { return _listb; } set { _listb = value; } } public override int GetHashCode() { return 1; } public override bool Equals(object obj) { return false; } public override string ToString() { return listb; } } ※長々と書き込みすいません、コード自体に意味はございません

  • HTML、CSS が、なかなかうまくいきません。

    お世話になります。 HTMLを始めたばかりですので、 ご教授いただけたら幸いです。 以下の図のような感じに並べたいのですが、 なかなかうまい具合にいきません。 黄色は、全てボタンになります。 赤は、ボタンについた吹き出し部分となります。 上段の2つのボタンは、やや大きい感じのボタン。 下段の3つのボタンは、上段に比べて、少し小さい感じのボタンになります。 ボタンは、上段(A)と下段(B)で、 HTML と CSS は、分けようかと考えています。 【HTML】 <div class="Button"> <div class="contents"> <div class="Button_boxA clearfix"> <div class="Yellow_Btn_01"><img src="img/Yellow_Btn_01.png" width="200" height="75" /> </div> <div class="Yellow_Btn_02"><img src="img/Yellow_Btn_02.png" width="200" height="80" /> </div> </div> <div class="btn_boxB clearfix"> <div class="Yellow_Btn_03"><img src="img/Yellow_Btn_03.png" width="100" height="60" /> </div> <div class="Yellow_Btn_04"><img src="img/Yellow_Btn_04.png" width="100" height="65" /> </div> <div class="Yellow_Btn_05"><img src="img/Yellow_Btn_05.png" width="100" height="60" /> </div> </div> </div> </div> 【 CSS 】 div.Button{ width:600px; margin-top:20px; margin-right:auto; margin-left:auto; padding-right:25px; } div.btn_boxA{ width::500px; margin-left:auto; margin-right:auto; margin-bottom:10px; } div.low_btn_01{ width:200px; height:75px; margin-left:auto; margin-right:auto; margin-bottom:10px; float:left; } div.low_btn_02{ width:200px; height:80px; margin-left:auto; margin-right:auto; padding-left:25px; margin-bottom:10px; float:left; } div.btn_boxB{ width::500px; margin-left:auto; margin-right:auto; margin-bottom:10px; } div.low_btn_03{ width:100px; height:60px; margin-left:auto; margin-right:auto; margin-bottom:10px; padding-left:25px; float:left; } div.low_btn_04{ width:100px; height:65px; margin-left:auto; margin-right:auto; margin-bottom:10px; padding-left:25px; float:left; ] div.low_btn_05{ width:100px; height:60px; margin-left:auto; margin-right:auto; margin-bottom:10px; padding-left:25px; float:left; } 長ったらしくなってしまいましたが、 ご教授いただけたら、幸いです。 宜しくお願いします。

    • 締切済み
    • CSS
  • WPF コントロールの参照

    Visualbasic 2010 を利用してWindows Formアプリケーションを開発しております。 Form上にWPF互換のためElementHostを配置し、その中にUserControlを配置しUserControl内にWPFのDataGridを配置しております。 CellTemplateを利用して1つのセル内に複数のTextBoxを配置しております。 ★Main.xaml 抜粋 <DataGridTemplateColumn > <!-- 表示時のセルのテンプレートを指定 --> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <local:Sien_Detail /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> ★Sien_Detail.xaml 抜粋 <TextBox x:Name="Label_0" Text="4/29(金)" HorizontalAlignment="Left" Margin="65,1,0,-19" TextWrapping="Wrap" Width="57" Background="{x:Null}" FontFamily="Arial" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontWeight="Bold" Foreground="Black" BorderBrush="#FFABADB3" IsReadOnly="True" IsTabStop="False" Height="18" /> <TextBox x:Name="Label_1" Text="4/30(土)" HorizontalAlignment="Left" Margin="127,1,0,-19" TextWrapping="Wrap" Width="57" Background="{x:Null}" FontFamily="Arial" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontWeight="Bold" Foreground="Black" BorderBrush="#FFABADB3" IsReadOnly="True" IsTabStop="False" RenderTransformOrigin="1.061,0.622" /> ★Sien_Detail.xaml.vb エラー箇所 Me.Controls("Label_0").Text = "ああ" そのTextBoxをプログラム側で制御したいと考えております。 Windows Formであれば[Me.Controls("TextBox1")]のようなコーディングで参照できるのですが、上記の場合、「Controlsはメンバーではありません」が表示されてしまいます。 どなたか改善策が分る方がいらっしゃいましたらご教授頂けますと幸いです。 以上です。

  • ルート要素に指定しているxmlnsについて教えて下さい。

    「Visual Studio 2008」の評価版を使用しています。 下記の記述はプロジェクトを作成した時に作成されたXAMLファイルです。 ※デフォルトです。 <UserControl x:Class="_sample.Page"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  Width="400" Height="300">  <Grid x:Name="LayoutRoot" Background="White">  </Grid> </UserControl> 「xmlns」と「xmlns:x」について教えて下さい。 「xmlns」・・・ XML名前空間 「xmlns:x」・・・ XAML言語の名前空間 下記のサイトに書いてありましたが・・・ http://msdn.microsoft.com/ja-jp/library/cc189036(VS.95).aspx#whatisxaml 私が知りたいのはこの「xmlns」と「xmlns:x」の属性は固定ですか。 ※固定というのはURLではありません。 くだらない質問かも知れませんがご教授、お願いします。 失礼します。

  • スマホ画面で長い文章が、左端に短い幅で片寄る。

    スマホ画面で長い文章の部分だけ折り返され、左端に短い幅で片寄ってしまいます。 これはどのように修正すれば良いのでしょうか。PCではいろんなブラウザで問題なく表示されています。 #header { width:100%; background:#cccc99; } #container { width:950px; margin-left:auto; margin-right:auto; text-align:left; } #col1 { width:740px; float:left; margin-left:20px; background:#383838; } #col2 { width:190px; float:left; } #footer { clear:left; width:100%; border-top:1px solid #8f8472; } 左側にメニュー(190px)を配置したレイアウトです。 h1,h2,P,liタグなど、とにかく長い文章の部分だけ、画面幅ではなく、短い幅で折り返され 左側に片寄っています。下記のxxxxxxxxの部分もそのようになります。 ul.abc { list-style:none; width:100%; margin: 0; padding: 0; } ul.abc li { float:left; margin-right:1em; padding: 0; } ul.abc a { float:left; line-height:85px; } ul.abc img { float:left; margin-right:.5em; vertical-align:middle; } <ul class="abc"> <li><a href="..." target="_blank"><img src="..." width="115" height="85" alt=""/><img src="..." height="1px" width="1px" border="0"> xxxxxxxxxxxxxxxxxxxxx</a></li> </ul><div style="clear: left;"></div> よろしくお願い致します。

    • 締切済み
    • CSS
  • firefoxでfloatの調整の仕方CSS

    CSSで下記(div)のなかにBOXを3つ並べました、 ie6以上では思い通りに表示されるのですがFireFox(バージョン3.5.3)では一番右端にくるBOXが左端のBOXの下に入ってしまいます。 どなたか解決策を教えていただけますでしょうか? ----ソース部分--- <div class="setbox1"> <div id="rent1"><a href="eee.html"><img src="img/trans_rent.gif" width="234" height="69" /></a></div> <div id="rent2"><a href="aaa.html"><img src="img/trans_rent.gif" width="234" height="69" /></a></div> <div id="rent3"><a href="ccc.html"><img src="img/trans_rent.gif" width="234" height="69" /></a></div> </div> ----以下CSS---- .setbox1{ margin-left : 25px; width : 750px; } #rent1{ margin-top : 20px; margin-left : 0px; float : left; width : 234px; } #rent1 a{ background-image : url(img/rent1.gif); display : block; line-height : 0px; background-repeat : no-repeat; width : 234px; height : 69px; } #rent1 a:hover{ background-position : left bottom; } #rent1 img{border-width : 0px 0px 0px 0px; } #rent2{ margin-left : 0px; float : left; margin-right : 22px; padding-left : 22px; width : 234px; margin-top : 20px; } #rent2 a{ background-image : url(img/rent2.gif); display : block; background-repeat : no-repeat; line-height : 0px; width : 234px; height : 69px; } #rent2 a:hover{ background-position : left bottom; } #rent2 img{border-width : 0px 0px 0px 0px; } #rent3{ margin-top : 20px; margin-left : 0px; padding-left : 0px; } #rent3 a{ background-image : url(img/rent3.gif); line-height : 0px; background-repeat : no-repeat; width : 234px; height : 69px; display : block; } #rent3 a:hover{ background-position : left bottom; } #rent3 img{border-width : 0px 0px 0px 0px; }