Wpf

WPFにコントロールを動的に追加し、コントロールのスタイルを指定します



Dynamically Add Controls Wpf



値を表示するには、リスト内のアイテム(リスト内の基本タイプ)ごとにTextBlockを作成する必要があります。コントロールをXamlで直接記述した場合、目的の効果が得られない可能性があります(ItemsControlsのようなコントロールを使用することはできません)。その後、プログラムを介してのみ動的に追加できます。このレコードを閉じます。
最初の方法:
Xamlでスタイルを作成するか、ユーザーコントロールをカスタマイズします。

TextBlock tb = new TextBlock() var textBinding = new Binding('MissionPoints[' + x + ']') textBinding.Mode = BindingMode.TwoWay tb.SetBinding(TextBlock.TextProperty, textBinding) // Write the following resource in Xaml and set the Style by looking up the resource. // // // // // // // tb.Style = this.FindResource('tbStyle') as Style this.grid1.Children.Add(tb) Grid.SetRow(tb, x)

この方法はXamlでスタイルを記述することであり、WPFの実装モードを理解するのは簡単ではありません。



2番目の方法:C#コードを完全に使用して実現します。

TextBlock tb = new TextBlock() var textBinding = new Binding('MissionPoints[' + x + ']') textBinding.Mode = BindingMode.TwoWay tb.SetBinding(TextBlock.TextProperty, textBinding) Binding dtBinding = new Binding() dtBinding.Path = new PropertyPath('Text') dtBinding.RelativeSource = new RelativeSource(RelativeSourceMode.Self) dtBinding.Converter = new DataConverter() DataTrigger dt = new DataTrigger() dt.Binding = dtBinding dt.Value = true Setter setter = new Setter() setter.Property = TextBlock.ForegroundProperty var brush = new System.Windows.Media.SolidColorBrush() brush.Color = Color.FromRgb(255, 0, 0) setter.Value = brush dt.Setters.Add(setter) Style style = new Style() style.TargetType = typeof(TextBlock) style.Triggers.Add(dt) tb.Style = style this.grid1.Children.Add(tb) Grid.SetRow(tb, x)

2番目の方法は、C#を使用して機能を実装することです。 WPFの実装原理を理解しやすい。しかし、私の最初のトリガーは機能しませんでした。その理由は、判断の価値が少なく書かれているからです。



dt.Value = true

したがって、コードを書くときは注意してください。

パブリッククラスDataConverter:IValueConverter

{ #region IValueConverter member public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return false if (string.IsNullOrEmpty(value.ToString())) return false if (!Regex.IsMatch(value.ToString(), '^[1-9]\d*$')) return false return System.Convert.ToInt32(value) > 0 } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException() } #endregion }

値がゼロより大きい場合、前景色は赤に設定されます。