StackPanelに動的にTextBlockを追加するため
ViewModel側でStackPanelを保持したいです。
コードビハインドでは「spanel.Children.Add(textBlock);」のように書くことができますが、
MVVMのViewModelで記載するにはどのようにすれば良いのでしょうか。
(DataContextにバインディングしようとしましたが、できていない気がします。)
イメージは下記のコードのLabelのように
ViewwModel側はプロパティで状態を保持し、変更がある度、
更新されるようにしたいです。
よろしくお願いします。
■View側
C#
<Window x:Class="Test1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:Test1" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <vm:Test1ViewModel /> </Window.DataContext> <Grid> <StackPanel DataContext="{Binding TestStackPanel}"/> <Label Content="{Binding TestLabel}" HorizontalAlignment="Left" VerticalAlignment="Top"/> </Grid> </Window>
■ViewModel側
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace Test1 { class Test1ViewModel : ViewModelBase { /// <summary> /// コンストラクタ /// </summary> public Test1ViewModel() { ShowList(); } private string _testLabel = "初期値"; public string TestLabel { get { return _testLabel; } set { if (value == _testLabel) { return; } } } private StackPanel _testStackPanel = new StackPanel(); public StackPanel TestStackPanel { get { return _testStackPanel; } set { if (value == _testStackPanel) { return; } } } private List<string> _itemList = new List<string>(); private void ShowList() { _itemList.Add("テスト1"); _itemList.Add("テスト2"); _itemList.Add("テスト3"); foreach (var item in _itemList) { // TextBlockのInlinesプロパティにRunを入れ込む var txtblock = new TextBlock(); txtblock.Inlines.Add(new Run { Text = item, Foreground = new SolidColorBrush(Colors.Red) }); // ここで動的に作成したTextBlockを追加したい // コードビハインドでは「spanel.Children.Add(textBlock); 」のように書ける TestStackPanel.Children.Add(txtblock); } } } }
(ViewModelBase)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Test1 { public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (Equals(storage, value)) return false; storage = value; return true; } } }
まだ回答がついていません
会員登録して回答してみよう