質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

コンボボックス

GUIの要素のひとつです。Listboxと同様にいくつかのうちひとつを選択する機能だが、Comboboxの場合は選択されたもののみがデフォルトとして表示される。

WPF

Windows Presentation Foundation (WPF) は、魅力的な外観のユーザー エクスペリエンスを持つ Windows クライアント アプリケーションを作成するための次世代プレゼンテーション システムです

Q&A

解決済

3回答

2921閲覧

【WPF】Dictonaryの値をコンボボックスに表示できない、クラスを参照したい

退会済みユーザー

退会済みユーザー

総合スコア0

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

コンボボックス

GUIの要素のひとつです。Listboxと同様にいくつかのうちひとつを選択する機能だが、Comboboxの場合は選択されたもののみがデフォルトとして表示される。

WPF

Windows Presentation Foundation (WPF) は、魅力的な外観のユーザー エクスペリエンスを持つ Windows クライアント アプリケーションを作成するための次世代プレゼンテーション システムです

1グッド

0クリップ

投稿2021/06/24 04:00

編集2023/07/28 01:12

前提・実現したいこと

初歩的な話で大変申し訳ないのですが、
組み方が良く分からないので質問させてください。

【WPF】Rectangleの線の色「Brushes.Red」などを、文字列で指定したい
https://teratail.com/questions/344646

上記で頂いている「TN8001」様の回答をもとに
データをClassファイルに分けて他のxamlからも参照出来るようにしたいと思っています。

・他から参照できるよう、NowData.csクラスに値を入れたい
Classを作成し、そこで値を共有(?)することは出来ています。
ただ、今回のは複雑だからか上手くいかず、コンボボックスに何も表示されません。

・全部のxamlから参照できるDictionaryは作成できるのか
(コンボボックスの選択肢項目は共通なので、1つの場所で管理出来たらいいなと思っています)

改変していますが、なぜコンボボックスに何も表示されないのか分からず
手詰まりの状態です。
コメントアウトしているところを、表示にしたり非表示にしたりしてテストしていました。

たぶん初歩的な話なのだと思いますが、
申し訳ありませんが教えて頂けると嬉しいです。

発生している問題・エラーメッセージ

xaml

1<Window x:Class="TEST1.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:TEST1" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="450" Width="800"> 9 10 <Window.Resources></Window.Resources> 11 12 <Grid> 13 <Grid.RowDefinitions> 14 <RowDefinition Height="Auto" /> 15 <RowDefinition /> 16 </Grid.RowDefinitions> 17 <DockPanel> 18 <TextBlock VerticalAlignment="Center" Text="線の色" /> 19 <ComboBox 20 x:Name="BordColorC2" 21 Margin="5" 22 ItemsSource="{Binding Colors}" 23 SelectedValue="{Binding DefoColors}" 24 SelectedValuePath="Key" 25 SelectionChanged="BordColorC2_SelectionChanged"> 26 <ComboBox.ItemTemplate> 27 <DataTemplate> 28 <DockPanel> 29 <Ellipse Width="16" Height="16" Fill="{Binding Value}" /> 30 <TextBlock Margin="5,0" VerticalAlignment="Center" Text="{Binding Key}" /> 31 </DockPanel> 32 </DataTemplate> 33 </ComboBox.ItemTemplate> 34 </ComboBox> 35 </DockPanel> 36 <Rectangle 37 Name="Rectan2" Grid.Row="1" Width="120" Height="100" Stroke="Black" StrokeThickness="2" /> 38 </Grid> 39</Window> 40

C#

1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Threading.Tasks; 6using System.Windows; 7using System.Windows.Controls; 8using System.Windows.Data; 9using System.Windows.Documents; 10using System.Windows.Input; 11using System.Windows.Media; 12using System.Windows.Media.Imaging; 13using System.Windows.Navigation; 14using System.Windows.Shapes; 15 16namespace TEST1 17{ 18 /// <summary> 19 /// MainWindow.xaml の相互作用ロジック 20 /// </summary> 21 /// 22 public partial class MainWindow : Window 23 { 24 public MainWindow() 25 { 26 InitializeComponent(); 27 } 28 29 private void BordColorC2_SelectionChanged(object sender, SelectionChangedEventArgs e) 30 { 31 var pair = (KeyValuePair<string, SolidColorBrush>)BordColorC2.SelectedItem; 32 Rectan2.Stroke = pair.Value; 33 } 34 } 35 36}

cs

1//NowData.cs 2using System; 3using System.Collections.Generic; 4using System.Linq; 5using System.Text; 6using System.Threading.Tasks; 7using System.Windows.Media; 8 9namespace TEST1 10{ 11 class NowData 12 { 13 public static string NowBordColor { get; set; } 14 } 15 16 //public static Dictionary<string, SolidColorBrush> Colors { get; } = 17 // new Dictionary<string, SolidColorBrush> 18 // { 19 // {"Red", Brushes.Red }, 20 // {"Blue", Brushes.Blue }, 21 // {"Green", Brushes.Green }, 22 // {"白", Brushes.White }, 23 // {"黒", Brushes.Black }, 24 // {"透明", Brushes.Transparent }, 25 // }; 26}

App.xaml

1<Application x:Class="TEST1.App" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:local="clr-namespace:TEST1" 5 xmlns:System="clr-namespace:System;assembly=mscorlib" 6 StartupUri="MainWindow.xaml"> 7 <Application.Resources> 8 <x:Array x:Key="Colors" Type="System:String"> 9 <System:String>Transparent</System:String> 10 <System:String>Red</System:String> 11 <System:String>Blue</System:String> 12 <System:String>Green</System:String> 13 <System:String>White</System:String> 14 <System:String>Black</System:String> 15 </x:Array> 16 </Application.Resources> 17</Application>

参考にさせて頂いているソース

xaml

1<Window 2 x:Class="Questions344646.MainWindow" 3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 5 xmlns:System="clr-namespace:System;assembly=mscorlib" 6 Width="600" 7 Height="400" 8 Background="LightGray"> 9 <Window.Resources> 10 <x:Array x:Key="Colors" Type="System:String"> 11 <System:String>Red</System:String> 12 <System:String>Blue</System:String> 13 <System:String>Green</System:String> 14 <System:String>White</System:String> 15 <System:String>Black</System:String> 16 <System:String>NoColor</System:String> 17 </x:Array> 18 </Window.Resources> 19 <Grid> 20 <Grid.ColumnDefinitions> 21 <ColumnDefinition /> 22 <ColumnDefinition /> 23 </Grid.ColumnDefinitions> 24 25 <GroupBox Header="BrushConverter"> 26 <Grid> 27 <Grid.RowDefinitions> 28 <RowDefinition Height="Auto" /> 29 <RowDefinition /> 30 </Grid.RowDefinitions> 31 <DockPanel> 32 <TextBlock VerticalAlignment="Center" Text="線の色" /> 33 <ComboBox 34 x:Name="BordColorC" 35 Margin="5" 36 ItemsSource="{StaticResource Colors}" 37 SelectedValue="{Binding DefoBordColor}" 38 SelectionChanged="BordColorC_SelectionChanged" /> 39 </DockPanel> 40 <Rectangle 41 Name="Rectan" 42 Grid.Row="1" 43 Width="120" 44 Height="100" 45 Stroke="Black" 46 StrokeThickness="2" /> 47 </Grid> 48 </GroupBox> 49 50 <GroupBox Grid.Column="1" Header="Dictionary"> 51 <Grid> 52 <Grid.RowDefinitions> 53 <RowDefinition Height="Auto" /> 54 <RowDefinition /> 55 </Grid.RowDefinitions> 56 <DockPanel> 57 <TextBlock VerticalAlignment="Center" Text="線の色" /> 58 <ComboBox 59 x:Name="BordColorC2" 60 Margin="5" 61 ItemsSource="{Binding Colors}" 62 SelectedValue="{Binding DefoBordColor2}" 63 SelectedValuePath="Key" 64 SelectionChanged="BordColorC2_SelectionChanged"> 65 <ComboBox.ItemTemplate> 66 <DataTemplate> 67 <DockPanel> 68 <Ellipse 69 Width="16" 70 Height="16" 71 Fill="{Binding Value}" /> 72 <TextBlock 73 Margin="5,0" 74 VerticalAlignment="Center" 75 Text="{Binding Key}" /> 76 </DockPanel> 77 </DataTemplate> 78 </ComboBox.ItemTemplate> 79 </ComboBox> 80 </DockPanel> 81 <Rectangle 82 Name="Rectan2" 83 Grid.Row="1" 84 Width="120" 85 Height="100" 86 Stroke="Black" 87 StrokeThickness="2" /> 88 </Grid> 89 </GroupBox> 90 </Grid> 91</Window>

C#

1using System.Collections.Generic; 2using System.ComponentModel; 3using System.Windows; 4using System.Windows.Controls; 5using System.Windows.Media; 6 7namespace Questions344646 8{ 9 public class DefaultData 10 { 11 public static string DefoBordColor 12 { 13 get => Properties.Settings.Default.DefaBordColor; 14 set => Properties.Settings.Default.DefaBordColor = value; 15 } 16 public static string DefoBordColor2 17 { 18 get => Properties.Settings.Default.DefaBordColor2; 19 set => Properties.Settings.Default.DefaBordColor2 = value; 20 } 21 22 public static Dictionary<string, SolidColorBrush> Colors { get; } = 23 new Dictionary<string, SolidColorBrush> 24 { 25 {"Red", Brushes.Red }, 26 {"Blue", Brushes.Blue }, 27 {"Green", Brushes.Green }, 28 {"白", Brushes.White }, 29 {"黒", Brushes.Black }, 30 {"透明", Brushes.Transparent }, 31 }; 32 } 33 34 public partial class MainWindow : Window 35 { 36 public MainWindow() 37 { 38 InitializeComponent(); 39 40 // xamlから逆算するとこうなっているってこと??(ちょっと変わってますね^^; 41 DataContext = new DefaultData(); 42 } 43 44 protected override void OnClosing(CancelEventArgs e) 45 { 46 Properties.Settings.Default.Save(); 47 } 48 49 private void BordColorC_SelectionChanged(object sender, SelectionChangedEventArgs e) 50 { 51 var name = BordColorC.SelectedItem.ToString(); 52 try 53 { 54 var brush = (SolidColorBrush)new BrushConverter().ConvertFromString(name); 55 Rectan.Stroke = brush; 56 } 57 catch 58 { 59 Rectan.Stroke = Brushes.Transparent; 60 } 61 } 62 63 private void BordColorC2_SelectionChanged(object sender, SelectionChangedEventArgs e) 64 { 65 var pair = (KeyValuePair<string, SolidColorBrush>)BordColorC2.SelectedItem; 66 Rectan2.Stroke = pair.Value; 67 } 68 } 69}

補足情報(FW/ツールのバージョンなど)

VisualStudio 2019
.NET Framework 4.5⇒4.7.2にバージョンアップ
WPF C# (※ WinFormではない)

TN8001👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

gentaro

2021/06/24 04:28

「.NET」だけで表記できるのは.NET 5からなんで「.NET Framework」じゃないの? 場合によっては回答が無駄になる可能性があるから、バージョンはしっかり確認してから書こう。
TN8001

2021/06/24 10:54

> ・他から参照できるよう、NowData.csクラスに値を入れたい 他からは参照するだけなのか、代入もあるのか? > public static string NowBordColor { get; set; } > Properties.Settings.Default.DefaBordColor 前回はSettings.settingsを使っていたがただのプロパティになっているのは省略しただけで、本来はSettingsを使う予定なのか? > ・全部のxamlから参照できるDictionaryは作成できるのか staticなDictionaryをxamlからバインドするのは、{x:Static local:NowData.Colors}とするだけです。 しかしNowBordColorも同様にすると、多数の落とし穴があって全然簡単な話ではないのです^^; 結局DataContext = new NowData();とするのが話が早い可能性がありますが、DataContextとは何かというところを理解する必要があります(これは基本であり一番の肝の部分です)
退会済みユーザー

退会済みユーザー

2021/06/24 23:47

TN8001様 回答ありがとうございます。 代入もあります。 ・全データ ・今参照しているデータ(全データの中の1行分のデータ) ・デフォルトで入れたいデータ(Settings.settings) この3種類のデータがあります。 今回のサンプル?として表示したものは、「今参照しているデータ」なので ただのプロパティとしました。 FillColorとBordColorがあるのですが、 コンボボックスの選択肢は共通として 選択後の値を別のプロパティに保存して管理出来たらなと思ってます。 これを3種類のデータで別管理するのもどうなのかと思ったため まとめられないかと思いました。 (頂いた内容に返事できているかどうか…すみません) BindingとかDataContextとか、中々難しく、まだ理解できてません。 良く利用されていることなので理解すべきとは思ってますが なんとなく。 DataContextは、全体の変数をまとめたファイル参照みたいなイメージで そこにあるXとかその他変数をBindingできるのかなという… 雑ですみません。
Zuishin

2021/06/25 23:02

Binding も DataContext もわからない縛りでプログラミングしなきゃいけないという拷問をなぜ選ぶのか。調べてもいいのなら調べればいいのに。
okazuki0130

2021/06/26 11:45

Binding は雑に言うとソースに設定されているオブジェクトのプロパティをコントロールのプロパティと同期をするためのものです。Binding の Source プロパティを省略した場合、Source は DataContext になります。なので「DataContextは、全体の変数をまとめたファイル参照みたいなイメージで そこにあるXとかその他変数をBindingできる」でおっしゃってるような動きをします。
guest

回答3

0

サンプルを更新しました。以下のように動きます。

イメージ説明

https://github.com/runceel/Teratail.Questions345835

なるべく元のコードを尊重したつもりです。変更点は以下のようになってます。

色情報の保持に関する変更

色の名前とブラシの対応付けをしたいようなので、NowData.cs に ColorInfo クラスを追加して、そこで色の名前とブラシの情報を持たせるようにしました。

csharp

1public class ColorInfo 2{ 3 public ColorInfo(string name, Brush brush) 4 { 5 Name = name; 6 Brush = brush; 7 } 8 public string Name { get; } 9 public Brush Brush { get; } 10} 11

NowData クラスで ColorInfo の配列としてコンボボックスに表示するデータを管理しています。また SelectedColor プロパティで選択された ColorInfo を管理するようにしています。
NowData クラスのインスタンスは static プロパティの Instance で管理して、MainWindow などの XAML からは、NowData の Instance プロパティを DataContext に設定することで状態の共有をしています。

csharp

1public class NowData : INotifyPropertyChanged // Binding 対応するために INofityPropertyChanged を実装 2{ 3 // 今回はここの NowData の static 変数でデータを管理するようにしています。 4 public static NowData Instance { get; } = new NowData(); 5 6 // Dictionary ではなく ColorInfo の配列にしました。 7 public ColorInfo[] Colors { get; } = new ColorInfo[] 8 { 9 new ColorInfo("Red", Brushes.Red ), 10 new ColorInfo("Blue", Brushes.Blue ), 11 new ColorInfo("Green", Brushes.Green ), 12 new ColorInfo("白", Brushes.White ), 13 new ColorInfo("黒", Brushes.Black ), 14 new ColorInfo("透明", Brushes.Transparent ), 15 }; 16 17 // 選択された ColorInfo を保持するプロパティ 18 private ColorInfo _colorInfo; 19 public ColorInfo SelectedColor 20 { 21 get => _colorInfo; 22 set 23 { 24 _colorInfo = value; 25 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedColor))); 26 } 27 } 28 29 public event PropertyChangedEventHandler PropertyChanged; 30}

XAML の書き方は GitHub の方を見てください。

Visual Studio で開く場合

Visual Studio Installer で .NET クロスプラットフォーム開発のチェックを入れると SDK Style のプロジェクトも開けるようになると思います。

イメージ説明

投稿2021/06/26 12:09

okazuki0130

総合スコア185

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2021/07/28 06:50

okazuki0130様 回答ありがとうございます! 体調を崩した上、パソコンが壊れてしまい 全然teratail開けませんでした。返信遅れて申し訳ありません。 なんとなくわかったような気がするのですが、まだきちんと理解が出来てないと思うので、じっくり読み込もうと思います。 サンプルもありがとうございます。動かして色々変更して動作を確認します!
guest

0

ベストアンサー

tarokoさんのここ1月弱の質問は、すべて関連しているんですよね?
Rectangleの移動リサイズまで考えると、だいぶ先が長そうですね^^;

・他から参照できるよう、NowData.csクラスに値を入れたい

データのもと(csv等から読む予定?)をどうやって表示するかを、MVVM的にやった場合の例です。

・全部のxamlから参照できるDictionaryは作成できるのか

追加順を保持したいとのことなので、OrderedDictionaryにしました(非ジェネリックなのでほんとにイヤなのですが^^;
OrderedDictionary クラス (System.Collections.Specialized) | Microsoft Docs

回答コードは3つのウィンドウがあります。

  • メインウィンドウ
    DataGridCanvas。編集・追加と可視化(マウスでは動きませんよ?^^;
  • DetailViewウィンドウ
    1件の詳細画面。編集も同期する。
  • DefaultSettingウィンドウ
    追加時デフォルト色の設定。Properties.Settingsを直接読み書きする。

基本的には親玉(MainWindow)がデータ(ViewModel)を保持し、欲しい人(DetailView)に参照を渡します。
場合によってはDefaultSettingのように、staticで(Properties.Settings)アクセスしてもいいでしょう。

INotifyPropertyChangedを実装しているクラス(RectanProperties.Settings)のプロパティは、変更が即Viewに反映されています(この気持ちのよさのため、長いプロパティを書いたのです^^

すごい見にくくて申し訳ありませんが、1万字に圧縮するためです。

xml:App.xaml

1<Application x:Class="Questions345835.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ShutdownMode="OnMainWindowClose" StartupUri="MainWindow.xaml"> 2 <Application.Resources> 3 <DataTemplate x:Key="template"> 4 <DockPanel> 5 <Ellipse Width="16" Height="16" Fill="{Binding Value}" /> 6 <TextBlock Margin="5,0" VerticalAlignment="Center" Text="{Binding Key}" /> 7 </DockPanel> 8 </DataTemplate> 9 </Application.Resources> 10</Application>

xml:MainWindow.xaml

1<Window x:Class="Questions345835.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:Questions345835" Width="800" Height="600" Left="200" Top="200"> 2 <Grid> 3 <Grid.ColumnDefinitions> 4 <ColumnDefinition /> 5 <ColumnDefinition /> 6 </Grid.ColumnDefinitions> 7 <ItemsControl ItemsSource="{Binding Rectans}"> 8 <ItemsControl.ItemsPanel> 9 <ItemsPanelTemplate> 10 <Canvas Background="WhiteSmoke" /> 11 </ItemsPanelTemplate> 12 </ItemsControl.ItemsPanel> 13 <ItemsControl.ItemContainerStyle> 14 <Style> 15 <Setter Property="Canvas.Top" Value="{Binding Top}" /> 16 <Setter Property="Canvas.Left" Value="{Binding Left}" /> 17 </Style> 18 </ItemsControl.ItemContainerStyle> 19 <ItemsControl.ItemTemplate> 20 <DataTemplate DataType="{x:Type l:Rectan}"> 21 <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="{Binding Fill}" Stroke="{Binding Border}" StrokeThickness="5" /> 22 </DataTemplate> 23 </ItemsControl.ItemTemplate> 24 </ItemsControl> 25 <DataGrid Grid.Column="1" AutoGenerateColumns="False" ItemsSource="{Binding Rectans}" SelectedItem="{Binding Current, Mode=TwoWay, TargetNullValue={x:Static CollectionView.NewItemPlaceholder}}" SelectionMode="Single"> 26 <DataGrid.Columns> 27 <DataGridTextColumn Binding="{Binding Left}" Header="Left" /> 28 <DataGridTextColumn Binding="{Binding Top}" Header="Top" /> 29 <DataGridTextColumn Binding="{Binding Width}" Header="Width" /> 30 <DataGridTextColumn Binding="{Binding Height}" Header="Height" /> 31 <DataGridTemplateColumn Header="Border"> 32 <DataGridTemplateColumn.CellTemplate> 33 <DataTemplate> 34 <ComboBox ItemTemplate="{StaticResource template}" ItemsSource="{x:Static l:Choices.Colors}" SelectedValue="{Binding Border, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Value" /> 35 </DataTemplate> 36 </DataGridTemplateColumn.CellTemplate> 37 </DataGridTemplateColumn> 38 <DataGridTemplateColumn Header="Fill"> 39 <DataGridTemplateColumn.CellTemplate> 40 <DataTemplate> 41 <ComboBox ItemTemplate="{StaticResource template}" ItemsSource="{x:Static l:Choices.Colors}" SelectedValue="{Binding Fill, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Value" /> 42 </DataTemplate> 43 </DataGridTemplateColumn.CellTemplate> 44 </DataGridTemplateColumn> 45 </DataGrid.Columns> 46 </DataGrid> 47 </Grid> 48</Window>

xml:DetailView.xaml

1<Window x:Class="Questions345835.DetailView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:Questions345835" Title="DetailView" Width="300" Background="WhiteSmoke" Left="1000" ResizeMode="NoResize" SizeToContent="Height" Top="450"> 2 <StackPanel Margin="5" DataContext="{Binding Current}"> 3 <TextBlock Text="Left" /> 4 <TextBox Text="{Binding Left, UpdateSourceTrigger=PropertyChanged}" /> 5 <TextBlock Text="Top" /> 6 <TextBox Text="{Binding Top, UpdateSourceTrigger=PropertyChanged}" /> 7 <TextBlock Text="Width" /> 8 <TextBox Text="{Binding Width, UpdateSourceTrigger=PropertyChanged}" /> 9 <TextBlock Text="Height" /> 10 <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged}" /> 11 <TextBlock Text="Border" /> 12 <ComboBox ItemTemplate="{StaticResource template}" ItemsSource="{x:Static l:Choices.Colors}" SelectedValue="{Binding Border, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Value" /> 13 <TextBlock Text="Fill" /> 14 <ComboBox ItemTemplate="{StaticResource template}" ItemsSource="{x:Static l:Choices.Colors}" SelectedValue="{Binding Fill, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Value" /> 15 </StackPanel> 16</Window>

xml:DefaultSetting.xaml

1<Window x:Class="Questions345835.DefaultSetting" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:Questions345835" xmlns:p="clr-namespace:Questions345835.Properties" Title="DefaultSetting" Width="300" Background="WhiteSmoke" Left="1000" ResizeMode="NoResize" SizeToContent="Height" Top="200"> 2 <StackPanel Margin="5"> 3 <Border Height="40" Margin="50,10" Background="{Binding SelectedItem.Value, ElementName=fill}" BorderBrush="{Binding SelectedItem.Value, ElementName=border}" BorderThickness="5" /> 4 <TextBlock Text="Border" /> 5 <ComboBox Name="border" ItemTemplate="{StaticResource template}" ItemsSource="{x:Static l:Choices.Colors}" SelectedValue="{Binding DefaultBorderColor, Source={x:Static p:Settings.Default}}" SelectedValuePath="Key" /> 6 <TextBlock Text="Fill" /> 7 <ComboBox Name="fill" ItemTemplate="{StaticResource template}" ItemsSource="{x:Static l:Choices.Colors}" SelectedValue="{Binding DefaultFillColor, Source={x:Static p:Settings.Default}}" SelectedValuePath="Key" /> 8 </StackPanel> 9</Window>

cs

1using CommunityToolkit.Mvvm.ComponentModel; 2using System.Collections.ObjectModel; 3using System.Collections.Specialized; 4using System.ComponentModel; 5using System.Windows; 6using System.Windows.Media; 7 8namespace Questions345835 9{ 10 // コンボボックスの選択肢クラス 11 public static class Choices 12 { 13 // ValueTupleはフィールドなのでバインドできず、Tupleは共変?じゃない 14 // OrderedDictionaryは非ジェネリックで悩ましい 15 public static OrderedDictionary Colors { get; } = 16 new OrderedDictionary 17 { 18 { "赤", Brushes.Red }, 19 { "青", Brushes.Blue }, 20 { "緑", Brushes.Green }, 21 { "白", Brushes.White }, 22 { "黒", Brushes.Black }, 23 { "透明", Brushes.Transparent }, 24 }; 25 } 26 27 // Rectangleの元データになるクラス 値の変更があるのでINotifyPropertyChangedを実装 28 public class Rectan : ObservableObject 29 { 30 // なんだか長いですが変更通知のため仕方がありません。定型コードと割り切ってください^^; 31 public double Left { get => _Left; set => SetProperty(ref _Left, value); } 32 private double _Left; 33 public double Top { get => _Top; set => SetProperty(ref _Top, value); } 34 private double _Top; 35 public double Width { get => _Width; set => SetProperty(ref _Width, value); } 36 private double _Width; 37 public double Height { get => _Height; set => SetProperty(ref _Height, value); } 38 private double _Height; 39 public Brush Border { get => _Border; set => SetProperty(ref _Border, value); } 40 private Brush _Border; 41 public Brush Fill { get => _Fill; set => SetProperty(ref _Fill, value); } 42 private Brush _Fill; 43 44 public Rectan() // 引数なしコンストラクタがないとDataGridで追加ができない 45 { 46 // とりあえず初期表示される値 47 (Left, Top, Width, Height) = (100, 100, 100, 100); 48 // デフォルトで入れたいデータ(Settings.settings)は直読み 49 Border = (Brush)Choices.Colors[Properties.Settings.Default.DefaultBorderColor]; 50 Fill = (Brush)Choices.Colors[Properties.Settings.Default.DefaultFillColor]; 51 } 52 } 53 54 public class ViewModel : ObservableObject 55 { 56 // 全データ 57 public ObservableCollection<Rectan> Rectans { get; } = new ObservableCollection<Rectan>(); 58 59 // 今参照しているデータ(全データの中の1行分のデータ) 60 public Rectan Current { get => _Current; set => SetProperty(ref _Current, value); } 61 private Rectan _Current; 62 63 public ViewModel() 64 { 65 // ファイルから読んでRectansに追加する等。とりあえず1件あったことにする 66 Rectans.Add(new Rectan()); 67 } 68 } 69 70 public partial class MainWindow : Window 71 { 72 // 場合によってはpublic staticで見せてもまあいいでしょう^^; 73 //public static ViewModel VM { get; } 74 75 public MainWindow() 76 { 77 InitializeComponent(); 78 var vm = new ViewModel(); // すべてのデータのもと newは1回だけ 79 DataContext = vm; 80 81 new DefaultSetting().Show(); 82 new DetailView { DataContext = vm, }.Show(); // ほしい人がいたら渡す 83 } 84 85 protected override void OnClosing(CancelEventArgs e) => Properties.Settings.Default.Save(); 86 } 87}

Settings.settings

アプリ画像


実はMouseDragElementBehaviorも試していたのですが、動的追加は未考慮(動かないわけではないがいろいろおかしい)のようでした。。。

投稿2021/06/25 22:37

編集2023/07/27 16:12
TN8001

総合スコア9244

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2021/07/28 06:47

TN8001様 毎度回答ありがとうございます!お世話になっております! 体調を崩した上、パソコンが壊れてしまい 全然teratail開けませんでした。返信遅れて申し訳ありません。 1か月弱の投稿は全て関連しており、 目的のものを作るのには技術も知識も何もかも足りないなと痛感してます。 WinFormの無いWPFのみの勉強サイトがあればと思いますが 中々良いのが無く(やりたいサンプルもないため)進みません。 というのも言い訳になりますので、もう少し色々と探してみようと思います。 丁寧にいろいろと記載頂きありがとうございます。 まだ少しボーっとしているところがあり、ちょっと読み解くのに時間がかかりそうです。 じっくり考え、覚えていこうと思います!とりあえず動くかテストし、変更してどう動くかなど試しながら覚えていきます。 ありがとうございました!
TN8001

2022/03/30 10:58

> 実はMouseDragElementBehaviorも試していたのですが、動的追加は未考慮(動かないわけではないがいろいろおかしい)のようでした。。。 初期値を <TranslateTransform X="{Binding Left}" Y="{Binding Top}" /> で突っ込めば狙った通りの動作になりました^^ [WPF C# 親ウィンドウと子ウィンドウのデータ共有](https://teratail.com/questions/jru5bj6b9xz7g1#reply-opovcszr6bj3zb)
guest

0

とりあえず元コードをそれっぽく動くようにしてみました。
でも、何を理解するためにこれを作っているのかわからないので最適かどうかはわかりません。

https://github.com/runceel/Teratail.Questions345835

  • 他から参照できるよう、NowData.csクラスに値を入れたい

恐らくやりたいことは「NowData クラスの Dictionary<string, SolidColorBrush> 型の静的プロパティの Colors にアプリケーション全体でグローバルにアクセスできる名前とブラシのペアを設定したい。」なのかなと理解しました。

Dictionary だと順序保障がない(追加した順番に要素が並ぶとは限らない)という特徴がありますが、そこらへんは大丈夫か心配になりました。

  • 全部のxamlから参照できるDictionaryは作成できるのか

出来ます。

投稿2021/06/24 10:59

編集2021/06/24 11:03
okazuki0130

総合スコア185

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

okazuki0130

2021/06/24 11:05

.NET Framework 4.5 はサポートが切れているので自分のマシンには入れたくないため .NET Framework 4.6.2 をターゲットにしています。
退会済みユーザー

退会済みユーザー

2021/06/25 00:05

okazuki0130様 サンプルありがとうございます。 .NET Framework 4.6.2のデベロッパー向けをダウンロードした後 ダウンロードして起動してみましたが 「無効なワークマップ」と表示されxamlが表示できませんでした。 参照アセンブリが失われているとか何とかで32もエラーがあります。 普通にcsファイルとかファイルの中をみるには問題ないので どのように記載して頂いているのか確認しようと思います。 できたら追加した順番にコンボボックスに表示したいと思ってます。 また、コンボボックスで選択した値は 別の場所に保持する必要があります。 別のxamlファイルからも何を選択しているのか参照でき、 コンボボックスに値を設定できる必要があります
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問