2017-10-28 3 views
0

단추 클릭 중에 TreeView 바인딩의 데이터 형식을 다른 형식으로 변경하고 싶습니다.WPF의 데이터 형식 변경 TreeView ItemsSource

이 코드는 TreeView입니다. 역할 유형을 StudentRoles에서 BursarRoles으로 변경하고 싶습니다.

<local:StudentRoles x:Key="MyData" /> 

정의

<local:BursarRoles x:Key="MyData" /> 

TreeView

에 : 예를 들어

<UserControl.Resources> 
    <local:StudentRoles x:Key="MyData" /> 
    <DataTemplate x:Key="LevelFour"> 
     <Border CornerRadius="5" > 
      <StackPanel Opacity=" 3"> 
       <TextBlock Text="{Binding Path=Name}" 
         Margin="5 5" 
       FontFamily="{StaticResource LatoRegular}" 
       FontSize="{StaticResource FontSizeMedium}" 
       Foreground="{StaticResource ForegroundVeryDarkBrush}" 
       /> 
      </StackPanel> 
     </Border> 
    </DataTemplate> 

    <HierarchicalDataTemplate x:Key="LevelThree" 
           ItemsSource="{Binding SubRoles}" 
           ItemTemplate="{StaticResource LevelFour}" 
           > 
     <StackPanel Margin="0 3"> 
      <TextBlock Text="{Binding Path=Name}" 
        Margin="2" 
        Foreground="{StaticResource ForegroundVeryDarkBrush}" 
        FontFamily="{StaticResource LatoRegular}" 
        FontSize="{StaticResource FontSizeMedium}" 
        /> 
     </StackPanel> 
    </HierarchicalDataTemplate> 

    <HierarchicalDataTemplate x:Key="LevelTwo" 
           ItemsSource="{Binding Roles}" 
           ItemTemplate="{StaticResource LevelThree}" 
           > 
     <StackPanel Margin="0 3"> 
      <TextBlock Text="{Binding Path=RoleDescription}" 
        Margin="2" 
        Foreground="{StaticResource ForegroundVeryDarkBrush}" 
        FontFamily="{StaticResource LatoRegular}" 
        FontSize="{StaticResource FontSizeLarge}" 
        /> 


     </StackPanel> 

    </HierarchicalDataTemplate> 

    <HierarchicalDataTemplate x:Key="LevelOne" 
           ItemsSource="{Binding UserRoles}" 
           ItemTemplate="{StaticResource LevelTwo}" 
           > 
     <StackPanel Margin="0 3"> 
      <TextBlock Text="{Binding Path=UserDescription}" 
        Margin="2" 
        Foreground="{StaticResource WordOrangeBrush}" 
        FontFamily="{StaticResource LatoRegular}" 
        FontSize="{StaticResource FontSizeXLarge}" 
        /> 
     </StackPanel> 

    </HierarchicalDataTemplate> 

</UserControl.Resources> 

<Grid x:Name="CanScrolGrid"> 
    <TreeView ItemTemplate="{StaticResource LevelOne}" 
       ItemsSource="{StaticResource MyData}" 
       Background="{StaticResource ForegroundLightBrush}" 
       /> 

    <Button Margin="10" HorizontalAlignment="Center" Height="40" Width="170" 
      Background="{StaticResource WordBlueBrush}" 
      Content="Change Roles" Click="Button_Click" /> 
</Grid> 

이의 UserControl 세트 역할 목록에 컨트롤의 DataContext, 예를 들어 StudentRoles의 뒤에 코드 케이스 :

public partial class RoleControls : UserControl 
{ 
    public RoleControls() 
    { 
     InitializeComponent(); 

     this.DataContext = new StudentRoles(); 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
    } 
} 

역할은 개별적으로 잘 작동하지만 런타임에 다른 역할로 데이터 컨텍스트를 변경할 수 있기를 원합니다. 그러나 나는 때문에이 라인의 너무 쉽게 수행 할 수 없습니다

<local:StudentRoles x:Key="MyData" /> 

어떻게 DataContext에 대한 변경을 허용하는 라인이 라인을 대체 할 수 있습니까? 당신이 게시 코드를 기반으로

/// <summary> 
/// The roles a student can perform on the system 
/// </summary> 

public class StudentRoles : BaseRole 
{ 
    #region Constructor 

    /// <summary> 
    /// Default Constructor 
    /// </summary> 
    public StudentRoles() 
    {  
     RoleType roleType; 
     Role role; 
     Role subRole; 
     UserType userRoles = new UserType("Student"); 

     #region Student Management 

     roleType = new RoleType("Stock Management"); 

     // Register product 
     role = new Role("Register Product"); 
     // Single 
     subRole = new Role("Single"); 
     role.SubRoles.Add(subRole); 
     // Multiple 
     subRole = new Role("Multiple"); 
     role.SubRoles.Add(subRole); 

     roleType.Roles.Add(role); 

     // Update product Status 
     role = new Role("Update Product Details"); 
     // Single 
     subRole = new Role("Single"); 
     role.SubRoles.Add(subRole); 
     // Multiple 
     subRole = new Role("Multiple"); 
     role.SubRoles.Add(subRole); 

     roleType.Roles.Add(role); 

     // View Product 
     role = new Role("View Product Details"); 
     // Single 
     subRole = new Role("Single"); 
     role.SubRoles.Add(subRole); 
     // by Brand 
     subRole = new Role("By Brand"); 
     role.SubRoles.Add(subRole); 

     // bY level 
     subRole = new Role("By Price"); 
     role.SubRoles.Add(subRole); 

     // by business Year 
     subRole = new Role("By Business Year"); 
     role.SubRoles.Add(subRole); 

     // Dismiss product 
     role = new Role("Delete Product"); 
     // Single 
     subRole = new Role("Single"); 
     role.SubRoles.Add(subRole); 
     // Multiple 
     subRole = new Role("Multiple"); 
     role.SubRoles.Add(subRole); 

     // Add the role the list of role type 
     roleType.Roles.Add(role); 

     userRoles.UserRoles.Add(roleType); 

     this.Add(userRoles); 

     #endregion 
    } 

    #endregion 
} 

답변

0

, 당신이 DataContext을 설정하지만 결코 실제로 사용하고 있습니다 나타납니다 :

다음은 역할의 샘플 목록 (StudentRoles)입니다.

좋은 Minimal, Complete, and Verifiable code example이 없으면 시나리오에서 가장 효과적 일 수있는 정보를 알 수 없습니다. 그러나 지금까지 공유 한 내용에서 우려되는 행을 삭제해야합니다. 나는. StudentRoles 또는 BursarRoles 객체를 선언하지 말고 현재 상태 및 사용자 입력에 따라 DataContext을 적절히 설정하십시오 (즉, 지금 수행중인 객체 StudentRoles 또는 버튼 클릭시 BursarRoles 객체).

물론이 경우 ItemsSource을 다르게 설정해야합니다. DataContextStudentRoles 또는 BursarRoles 개체가 있고 TreeView 요소에 사용하려는 경우 ItemsSource="{Binding}" 만 사용할 수 있습니다. 예컨대 :

<TreeView ItemTemplate="{StaticResource LevelOne}" 
      ItemsSource="{Binding}" 
      Background="{StaticResource ForegroundLightBrush}"/> 

더 나은 당신이 필요에 따라 설정할 수있는 BaseRole 속성, 뷰의 최상위 뷰 모델을 생성하는 것이다. 그런 다음 ItemsSource은 예를 들어 ItemsSource="{Binding CurrentRoles}", 여기서 CurrentRoles은 필요에 따라 설정 한 최상위보기 모델의 속성입니다.

다음 최상위 뷰 모델도 명령 대상 방법은 CurrentRoles 속성을 변경 (단추의 Command 속성에 바인딩 즉) 버튼을 처리하는 명령 객체를 갖는 ICommand 속성을 가질 수 있고, 그 방법을 완료.

관련 문제