컨트롤을 참조하 WPF DataTemplate
-
03-07-2019 - |
문제
에 WPF 페이지에 나는 디자인에 대한 내 교회,나는 두 개의 ListBox 제어하는 바인딩은 결과를 두 개의 Linq-to-체 검색어:첫 번째 목록 상자/쿼리를 포함하는 모든 사람들이 아직기로 약속한,올해 두 번째 listbox/쿼리를 포함하는 모든 사람들을 약속했습니다(및 관련 약속).특별히:
var familiesWithNoPledges = from family in entities.Family.Include("Pledge")
where !family.Pledge.Where(p => p.PledgeYearID == pledgeYear).Any()
select family;
var familiesWithPledges = from family in entities.Family
join pledge in entities.Pledge.Include("PledgeFrequency").Where(p => p.PledgeYearID == pledgeYear) on family equals pledge.Family
select new { family, pledge };
할 때 응용 프로그램의 사용자 선택 가족에서 첫 번째 ListBox,ListBox 항목 확대에 약간 표시 분야에 대한 약속,그래서는 간편하게 추가할 수 있습니다 서약 정보 두 번째 목록 상자.그것은 다음과 같이 나타납니다.
http://wouldbetheologian.com/images/PledgeManager.jpg (외부 이미지)
기본 데이터베이스(다른 것들 사이)는"가족"table1:관계하여"약속"이다.과를 클릭할 때 추가"약속"버튼을 내가 만들고 싶은 새로운 약속 인스턴스,데이터베이스에 저장하고 다음 새로 고침을 두 제어합니다.
그러나 나는 방법을 알아낼 수 없습니다.면 내가 그것을 하려고 코드에서 뒤에,그것같이 보이지 않는 이벤트에 대한 처리기(n-의 인스턴스)"추가 약속"버튼을 참조할 수 있 컨트롤 질문;와 XAML,는 경우에도 바인딩 ListBoxItem DataTemplate 컨트롤습니다.서약(또는 가족입니다.약속입니다.FirstOrDefault())분야,해당 필드가 여전히 비어 있을 때 나는 현재 가족에서 객체의 이벤트 처리기 위해 추가 서약 버튼입니다.
어떤 생각을 해결하는 방법에 대한 이?또는 더 나은 UI 모델을 나는 찾아야에서 모두?
미리 감사드립니다.
해결책 2
감사,Andrew,는 않았습니다.키었다는 것을 만들 수 있었다 별도의 매핑되는 대 DockPanel 에서 질문한 다음,이 새 인스턴스의 약속 개체들에서 더 높은 템플릿입니다.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.Resources>
<local:Pledge x:Key="pledge" />
</Grid.Resources>
<DockPanel DataContext="{Binding Source={StaticResource pledge}}" >
<TextBox Name="txtAmount" Text="{Binding Path=Amount}" />
<TextBox Name="txtEnvelopeID" Text="{Binding Path=EnvelopeID}" />
<!-- Bind the Tag property of the Button to the DataContext of the ListBoxItem, i.e. the current Family object -->
<Button Tag="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DataContext}" Name="addPledge" Click="addPledge_Click" >
Add Pledge -->
</Button>
</DockPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
내가 여전히 필요한 자세한 내용을 알아 보려면 설치 서약 개체에 적합하게,하지만 난 그들을 얻을 수 있었다 바인딩하여 단추의 태그 속성을 매핑되의 템플릿 부모:
<Button
Tag="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DataContext}"
Name="addPledge"
Click="addPledge_Click"
/>
그리고 거기에서,을 처리 할 수 있었다 나머지 부분에 코드김:
private void addPledge_Click(object sender, RoutedEventArgs e)
{
try
{
// Set any additional necessary properties.
Button button = (Button)sender;
Pledge pledge = (Pledge)button.DataContext;
pledge.PledgeYear = (PledgeYear)cboYear.SelectedItem;
pledge.Family = (Family)button.Tag;
// Update the database and refresh the Listboxes.
entities.AddToPledge(pledge);
entities.SaveChanges();
LoadUnpledgedListBox();
LoadPledgedListBox();
}
catch (System.Data.UpdateException ex)
{
MessageBox.Show("Error updating database: " + ex.Message);
}
catch (System.Exception ex)
{
Classes.Utils.HandleGenericError(ex);
}
}
많은 감사--는 지적이 나서 오른쪽 방향입니다.
다른 팁
가장 쉬운 방법은 ListBox 항목에 항목을 나타내는 클래스를 사용하여 데이터 emplate에서 참조하는 모든 필드를 갖도록하는 것입니다. 그런 다음 버튼 핸들러에서 버튼의 데이터 컨텍스트를 사용하여 새로운 서약 정보에 액세스 할 수 있습니다.
private void AddPledge_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
PotentialPledge p = b.DataContext as PotentialPledge;
//do stuff with pledge
}
템플릿 필드를 클래스의 일부가되지 않고이 작업을 수행 할 수있는 방법이있을 수 있습니다. ListBox (WPF 직접 학습)의 항목 소스를 구성하는 클래스의 일부가 될 수 있지만, 이것이 작동합니다. 그게 도움이되지 않으면 나중에 다시 살펴 보겠습니다 (지금 일하러).
어쨌든, 당신의 교회를위한 앱을 만드는 멋진 일, 그것은 꽤 좋아 보인다.