[問題] WPF DataTemplate Binding Command Fail
問題是這樣的(已解決)
我有一個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);
}
}
--
推
09/05 19:33,
09/05 19:33
推
09/05 19:34,
09/05 19:34
推
09/05 19:38,
09/05 19:38
推
09/05 19:39,
09/05 19:39
推
09/05 19:56,
09/05 19:56
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.75.101.50 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1572422939.A.D8F.html
→
10/30 16:24,
5年前
, 1F
10/30 16:24, 1F
這個問題我只要願意用Click去做就可以秒解了....
→
10/30 16:28,
5年前
, 2F
10/30 16:28, 2F
→
10/30 16:29,
5年前
, 3F
10/30 16:29, 3F
※ 編輯: e23882 (211.75.101.50 臺灣), 11/14/2019 14:42:38
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章