作者e23882 (呆呆要不要买降有)
看板C_Sharp
标题[问题] WPF DataTemplate Binding Command Fail
时间Wed Oct 30 16:08:56 2019
问题是这样的(已解决)
我有一个DataGrid希望透过DataBinding的方式去设定资料
但是在指定Column除了显示资料外还要多一颗按钮可以做其他事情
https://imgur.com/a/fGrnv7W
资料我有Binding到了但是按钮没有成功Binding到Command
看Code很烦所以我简单描述一下我的ViewModel长怎样
DataModel
{
UserId
.
.
.其他栏位.
...
}
ViewModel
{
public ObservableCollection<DataModel>
GridSource
public Command
ButtonClickCommand
}
我在想是不是因为ItemSource只Binding到GridSource
他的DataTemplate里的Button没办法从父层找到Command
所以我就在Command後面加了一段Code从最外层(window)去找要Binding的Command
Command="{Binding ButtonChooseUserIdClick,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type Window}}}"
结果也是没找到,想请教一下这个失败的原因是什麽
*********************************************************************
我自己找到解决方法了
Command="{Binding RelativeSource={ RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.ButtonChooseUseridClick}"
加Path上去然後选DataContext里对应的Command就可以了
思考的方向应该没有错,就是Button在DataGrid里面
DataGrid因为Itemsource有Binding属性了,所以Button没有办法找到他要的东西
就改从window去找(this.DataContext = ViewModel)
但因为没有指定RelativeSource的Path要哪个属性所以没有Binding成功
*********************************************************************
Code大概长这样
Xaml:
<DataGrid ItemSource={Binding GridSource}>
<DataGrid.Columns>
<DataGridTemplateColumn Header="标题">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Stackpanel Oriented="Horizontal">
<TextBox Text={Binding UserId}/>
<Button Content="." Command="{Binding ButtonCommand}"/>
</...>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
CodeBehind:
public MainWindow()
{
init..();
MainViewModel mv = new MainViewModel();
this.DataComtext = mv;
}
ViewModel:
public void ViewModel:INotifyPropertyChanged
{
public void OnpropertyChanged(string propertyName){....}
private ObservableCollection<DataModel> _GridSource = new ...;
public ObservableCollection<DataModel> GridSource
{
get{return _GridSource;}
set{_GridSource = value;OnPropertyChanged("GridSource");}
}
public Command ButtonCommand{get;set;}
public void ButtonCommandAction(){//do something..}
//ViewModel建构子
public ViewModel()
{
ButtonCommand = new Command(ButtonCommandAction);
}
}
--
1F:推 staminafish:我国中都全校前10名09/05 19:33
2F:推 montes3388: 全校有10个人09/05 19:34
3F:推 twdonny: 其中5个缺席09/05 19:38
4F:推 montes3388: 4个资源斑09/05 19:39
5F:推 a110002211: 1个乡民09/05 19:56
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 211.75.101.50 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1572422939.A.D8F.html
6F:→ testPtt: 最近我都用click直接call datacontext... 10/30 16:24
这个问题我只要愿意用Click去做就可以秒解了....
7F:→ testPtt: 我之前写的<Button Command="{Binding DataContext.cmd 10/30 16:28
8F:→ testPtt: 也是加上DataContext 10/30 16:29
※ 编辑: e23882 (211.75.101.50 台湾), 11/14/2019 14:42:38