【发布时间】:2021-10-21 03:03:44
【问题描述】:
我有一个绑定到 ObservableCollection“菜单按钮”的 ItemsControl。 在 ItemsControl 中,我想通过依赖属性以编程方式添加一些按钮。
我的问题是我传递的值没有更新。默认值显示在视图中。
C#
private void btnTest_Click(object sender, RoutedEventArgs e)
{
var vm = DataContext as UflMainWindowViewModel;
vm.MenuButtons.Add(new UflMenuButton { IconText="Test123", Style = (Style)Application.Current.Resources["UflMenuButtonStyle"] });
}
C#UflButtonClass
public class UflMenuButton : Button
{
public string IconText
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("IconText", typeof(string), typeof(UflMenuButton), new UIPropertyMetadata("default", new PropertyChangedCallback(IconTextChanged)));
private static void IconTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
UflMenuButton button = (UflMenuButton)sender;
button.IconText = (string)e.NewValue;
}
}
具有以下样式:
WPF
<Style x:Key="UflMenuButtonStyle" TargetType="{x:Type local:UflMenuButton}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=(local:UflMenuButton.IconText),RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
【问题讨论】:
-
你能显示传递值的代码吗?
-
通过以下命令在第一个代码块中的 Button Click 事件中传递值:
IconText="Test123",... -
问题是“添加按钮后,按钮不显示”。对吗?
-
不,按钮已显示,但按钮文本块中的值不是“Test123”。它包含 DependencyProperty “default”的默认值
-
试试
<TextBlock Text="{Binding IconText}"...
标签: c# observablecollection dependency-properties itemscontrol