2016-07-25 2 views
0

동일한 UserControl을 두 번 인스턴스화합니다. 둘 다 Radiobutton을 가지고 GroupName을 공유합니다. 하나를 선택하면 다른 UserControl 인스턴스의 일부인 경우에도 다른 모든 사용자가 선택을 취소합니다.사용자 정의 사용자 정의 컨트롤과 WPF 라디오 버튼 그룹 충돌

이 GroupName 충돌을 어떻게 방지 할 수 있습니까?

<Window x:Class="RadioDemo.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel> 
     <UserControl x:Name="First"/> 
     <UserControl x:Name="Second"/> 
    </StackPanel> 
</Window> 

홈페이지 Codebehind가

public MainWindow() 
{ 
    InitializeComponent(); 
    Loaded += MainWindow_Loaded; 
} 

void MainWindow_Loaded(object sender, RoutedEventArgs e) 
{ 
    First.Content = new MyRadio(); 
    Second.Content = new MyRadio(); 
} 

MyRadio XAML

<UserControl x:Class="RadioDemo.MyRadio" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <StackPanel> 
     <RadioButton GroupName="G" x:Name="RadioOne" Content="RadioOne"/> 
     <RadioButton GroupName="G" x:Name="RadioTwo" Content="RadioTwo"/> 
    </StackPanel> 
</UserControl> 

답변

2

당신은 GR을 만들 수 있습니다

홈페이지 XAML : 여기

는 점을 설명하기 위해 최소한의 예입니다 사용자 정의 컨트롤이로드되면 동적으로 이름 값이 변경됩니다.

XAML :

<StackPanel> 
    <RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioOne" Content="RadioOne"/> 
    <RadioButton GroupName="{Binding GroupNameValue}" x:Name="RadioTwo" Content="RadioTwo"/> 
</StackPanel> 

보기 모델 :

private string groupNameValue = Guid.NewGuid().ToString(); 

public string GroupNameValue 
{ 
    protected get { return this.groupNameValue; } 
    set 
    { 
     this.SetProperty(ref this.groupNameValue, value); 
    } 
} 

SetPropertyINotifyPropertyChanged의 구현입니다.
고유성을 보증하기 위해 Guid을 사용했지만 원하는지 여부를 사용할 수 있습니다. C# 6.0 코드와

단순화 할 수있다 :

private string groupNameValue = Guid.NewGuid().ToString(); 

public string GroupNameValue => this.groupNameValue; 
+0

클린 솔루션, 또 다른 방법은 그룹 이름을 유지하는 UserControl을에 의존 propertery를 선언하는 것입니다. 필요에 따라 여러 개의 UC에 동일한 GroupName을 연결할 수 있습니다. – Funk

관련 문제