wpf,这个命令为什么换个位置就无效

货郎大叔 2018-09-12 06:39:53
自定义控件CustomControl3:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">
<Style TargetType="{x:Type local:CustomControl3}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl3}">
<Grid Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Name="txt" Width="100" Height="30"/>
<Button Grid.Row="1" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl3}},
Path=XiongJunCommand}" CommandParameter="{Binding ElementName=txt,Path=Text}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>


<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:CustomControl3/>
</Grid>
</Window>


public class CustomControl3 : Control
{
static CustomControl3()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl3), new FrameworkPropertyMetadata(typeof(CustomControl3)));
}
public CustomControl3()
{
Loaded += CustomControl3_Loaded;
XiongJunCommand = new RelayCommand<string>((param) => MessageBox.Show("你好" + param.ToString()));
}
private void CustomControl3_Loaded(object sender, RoutedEventArgs e)
{
// XiongJunCommand = new RelayCommand<string>((param) => MessageBox.Show("你好" + param.ToString()));
}
public RelayCommand<string> XiongJunCommand { get; set; }
}

在上面的代码中,命令XiongJunCommand放在CustomControl3构造函数中初始化,就会有效果,如果放在CustomControl3_Loaded事件函数中初始化,就没有效果。
这是唱的哪一出啊?
...全文
91 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
x8bits 2018-09-12
  • 打赏
  • 举报
回复
也可以把XiongJunCommand改成以DependencyProperty的方式实现
x8bits 2018-09-12
  • 打赏
  • 举报
回复
因为在xxx_Loaded时,WPF已经完成绑定(Binding):解决方法是实现IPropertyChange接口,然后在XiongJunCommand的设置(setter)里面通知WPF属性已变,这样WPF才能刷新命令绑定。

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧