2009-05-13 7 views
1

내 MainWindow.xaml의 코드 숨김 파일에서 .xaml 파일의 단추에 액세스하려고합니다. 파일에서 x : Class를 사용하려고했지만 버튼을 사용할 때 작동하지만 다른 많은 오류가 발생합니다. 그래서 나는이 방법을 사용하지 않는 것을 선호한다.<ResourceDictionary>의 WPF 액세스 컨트롤

mainWindows 클래스에서 템플릿을 사용하여 컨트롤에 액세스하는 다른 방법이 있습니까?

코드 :

<ResourceDictionary xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
       xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' 
       xmlns:l="clr-namespace:Avalon.Demo" x:Class="Bildbanken.MainWindow"> 

     <!-- Taggarnas placering under bilderna (Left/ Top/ Right/ Bottom) --> 
         <Label Content="{Binding Type}" Padding="0,5,7,0" HorizontalAlignment="Right" /> 
         <Label Content="{Binding Category}" Padding="7,0,0,0" /> 
         <ListBox Name="ArtInfo" ItemsSource="{Binding Articles}" BorderThickness="0" Background="{TemplateBinding Background}"> 
          <ListBox.ItemTemplate> 
           <DataTemplate> 
            <Grid> 
             <Grid.ColumnDefinitions> 
              <ColumnDefinition Width="115px" /> 
              <ColumnDefinition Width="auto" /> 
             </Grid.ColumnDefinitions> 
             <TextBlock Grid.Column="0" Text="{Binding Artnr}"></TextBlock> 
             <Button HorizontalAlignment="Right" Name="testbutton" Grid.Column="1">--</Button> 
            </Grid> 
           </DataTemplate> 
          </ListBox.ItemTemplate> 
         </ListBox> 
+0

지정해주십시오. 템플릿의 버튼을 참조하려고하는 이유는 무엇입니까? 나는 틀릴 수도 있지만 99.9 %에서 WPF에서 그런 일을하는 것은 나쁜 습관입니다. – arconaut

답변

0

데이터 형식의 내용에 액세스 할 수 있습니다. 이 같은 템플릿의 루트 요소를 얻을 수 있습니다 :

거기에서
UIElement templateRoot = listbox.ItemTemplate.LoadContent() as UIElement; 

, 당신은 Button 컨트롤을 찾기 위해 VisualTreeHelper를 사용합니다.

버튼 클릭 만 처리하려는 경우 WPF의 RoutedEvents를 사용하는 것이 더 좋습니다.

AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_Click)); 

이것은 소스에 관계없이 모든 버튼 클릭을 가져옵니다. 단추에 태그를 지정하면 원하는 단추 만 필터링 할 수 있는지 테스트 할 수 있습니다.

0

CommandBinding을 통해 DataTemplate과 단추에 추가 할 수있는 RoutedCommand를 지정할 수 있습니다. 당신이 버튼 클릭/명령을 처리 할 수있는 방법은 코드 뒤에서 예를 들어 실행하고 VisualTreeHelper (또는 내 tipp는 SomeElement.TryFindResource ("ButtonKey")가 될 수 있음)를 통해 버튼을 찾을 필요가 없습니다.

내가 원하는 것을 지우거나 내가 당신이 버튼으로하고 싶은 일을 이해하지 못했습니까?

0

먼저 명령을 등록한 .cs 파일을 만드십시오. 이 이름은 MyCommandCollection.cs 일 수 있습니다. 이 클래스에서 정의하고 사용하여 RoutedCommand 등록 :

public static readonly RoutedCommand ButtonPressCommand= new RoutedCommand("ButtonPress", typeof(MyCommandCollection)); 

당신은 UserControl을하거나 창에서 명령을 정의하면, 예를 들어 이내에 사용하려면 당신은 당신의 명령의 실행/CanExecute 메소드를 구현하여 UserControl을/윈도우의 코드 숨김에서

<UserControl.CommandBindings> 
    <CommandBinding Command="Commands:MyCommandCollection.ButtonPressCommand" Execute="Execute_ButtonPressCommand" ... /> 
</UserControl.CommandBindings> 

.

당신이 그런 예를 들어, ResourceDictionary에도 사용할 수 있습니다 그 방법 :

<Button Command="Commands:MyCommandCollection.ButtonPressCommand" /> 

도 UserControl을/윈도우와에 "MyCommandCollectionClass.cs"의 네임 스페이스를 넣어하는 것을 잊지 마세요 ResourceDictionary, 예를 들면 :

xmlns:Commands="clr-namespace:MyApp.SomeFolder.Commands" 

희망이 있습니다.

0

템플릿의 내용에 대한 코드 숨김이 필요하다면 일반적으로 템플릿 내용을 사용자 정의 컨트롤로 옮기는 것이 좋습니다. (코드 비하인드가 필요하지 않은 경우에도 종종 좋은 생각입니다.)

answer to another question은 기술을 보여줍니다. 질문은 관련있는 것 같지 않지만 대답은 내가 여기에서 주장하는 것과 동일한 접근 방식을 포함하고 있습니다. 예를 들어 계층 적 템플릿을 사용하는 경우도 있지만 일반 템플릿에도 적용 할 수 있습니다.

사용자 컨트롤은 두 가지 이점을 제공합니다 이리. 첫째, 지나치게 복잡한 Xaml 파일을 피하는 데 도움이됩니다. 템플릿을 자체 파일로 분리하지 않고 인라인 모드로두면 템플릿이 Xaml 파일을 쉽게 제어 할 수 있습니다. 둘째, 코드 숨김을 쉽게 사용할 수 있습니다.

나는 처음부터 코드 숨김을 피하도록 옹호하는 여러 가지 다른 답변에 동의한다. (저는 특정 솔루션에 동의하지 않습니다. 명령 기반 접근 방식을 사용하지만, 사용하지 않습니다. RoutedCommand - 일반적으로 DelegatingCommand 또는 RelayCommand라고하는 패턴을 따르는 ICommand의 사용자 지정 구현을 사용합니다. Xaml을 단순화하기 위해 사용자 정의 컨트롤로 템플릿 본문을 거의 정의합니다.