前提・実現したいこと
XAMLアプリのComboBoxのリストに値を動的に追加したいと考えております。
ただし同じ選択が出来るComboBoxが複数あり、
(実際はComboBoxはもっと数多くあり、一つ一つItemSourceをセットしていく事は難しい)
1つのItemSourceの更新で複数のComboBoxに同時に反映する必要があります。
Window.ResourcesからBindingする事で、同じ選択値を持つComboBoxを作る事は出来ましたが、
動的に追加する事がどうしてもできずにおり、方法を教えて頂けないでしょうか。
該当のソースコード
XAML
1<Window x:Class="WpfApp1.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:WpfApp1" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="200" Width="400"> 9 <Window.Resources> 10 <local:TestList x:Key="testlist" /> 11 </Window.Resources> 12 <Grid> 13 <StackPanel Orientation="Horizontal" > 14 <Button Click="Button_Click" Content="ButtonA" Width="100" /> 15 <ComboBox x:Name="combo1" VerticalContentAlignment="Center" DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource testlist}}" IsSynchronizedWithCurrentItem="False" Width="100"/> 16 <ComboBox x:Name="combo2" VerticalContentAlignment="Center" DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource testlist}}" IsSynchronizedWithCurrentItem="False" Width="100"/> 17 <ComboBox x:Name="combo3" VerticalContentAlignment="Center" DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource testlist}}" IsSynchronizedWithCurrentItem="False" Width="100"/> 18 </StackPanel> 19 </Grid> 20</Window> 21
該当のソースコード
C#
1using System.Collections.Generic; 2using System.Windows; 3 4namespace WpfApp1 5{ 6 public partial class MainWindow : Window 7 { 8 public MainWindow() 9 { 10 InitializeComponent(); 11 } 12 13 private void Button_Click(object sender, RoutedEventArgs e) 14 { 15 var testlist = FindResource("testlist") as TestList; 16 testlist.Add(new Test() { Name = "4", Val = "ddddd" }); // <--このボタンクリックによりComboBoxに値を追加したい。 17 } 18 } 19 20 public class TestList : List<Test> 21 { 22 public TestList() 23 { 24 this.Add(new Test() { Name = "1", Val = "aaaaa" }); 25 this.Add(new Test() { Name = "2", Val = "bbbbb" }); 26 this.Add(new Test() { Name = "3", Val = "CCCCC" }); 27 } 28 } 29 30 public class Test 31 { 32 public string Name { get; set; } 33 public string Val { get; set; } 34 } 35}
補足情報(FW/ツールのバージョンなど)
.NetFramework 4.5

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/23 04:14