programing

토글 버튼 그룹을 WPF의 라디오 버튼처럼 동작시키는 방법

nicescript 2023. 4. 22. 22:51
반응형

토글 버튼 그룹을 WPF의 라디오 버튼처럼 동작시키는 방법

전환 버튼과 같은 기능을 하는 버튼 그룹이 있지만 동시에 하나의 버튼만 선택하거나 누를 수 있는 라디오 버튼도 있습니다.또한 버튼이 선택/누르지 않은 상태여야 합니다.

동작은 Photoshop 툴바와 비슷하며, 이 툴은 항상 0개 또는 1개가 선택됩니다.

WPF에서 어떻게 구현될 수 있는지 아십니까?

내 생각에 이것이 가장 쉬운 방법이다.

<RadioButton Style="{StaticResource {x:Type ToggleButton}}" />

즐기세요! - Pricksaw

가장 쉬운 방법은 ItemTemplate에 ToggleButtons를 사용하는 ListBox 스타일링입니다.

<Style TargetType="{x:Type ListBox}">
    <Setter Property="ListBox.ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <ToggleButton Content="{Binding}" 
                              IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"
                />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

그런 다음 ListBox의 SelectionMode 속성을 사용하여 SingleSelect vs MultiSelect를 처리할 수 있습니다.

<RadioButton Content="Point" >
    <RadioButton.Template>
        <ControlTemplate>
            <ToggleButton IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                          Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"/>
        </ControlTemplate>
    </RadioButton.Template>
</RadioButton>

난 괜찮아, 즐겨!

항상 모든 ToggleButton을 설정하는 ToggleButton의 Click에서 일반 이벤트를 사용할 수 있습니다.그룹 컨트롤(Grid, WrapPanel 등)에서 IsChecked를 사용하여 false로 설정한 후 발신인을 다시 확인합니다.뭐 그런 거 있잖아요

private void ToggleButton_Click(object sender, RoutedEventArgs e)
    {
        int childAmount = VisualTreeHelper.GetChildrenCount((sender as ToggleButton).Parent);

        ToggleButton tb;
        for (int i = 0; i < childAmount; i++)
        {
            tb = null;
            tb = VisualTreeHelper.GetChild((sender as ToggleButton).Parent, i) as ToggleButton;

            if (tb != null)
                tb.IsChecked = false;
        }

        (sender as ToggleButton).IsChecked = true;
    }

라디오 버튼이 있는 그리드를 삽입하고 Raduio button용 템플릿과 같은 버튼을 만들 수 있습니다.버튼을 전환하지 않으려면 단순히 프로그램 삭제 체크만 하는 것이 아닙니다.

시험해 볼 수도 있습니다.System.Windows.Controls.Primitives.ToggleButton

 <ToggleButton Name="btnTest" VerticalAlignment="Top">Test</ToggleButton>

그런 다음 에 대해 코드를 작성합니다.IsChecked라디오 버튼 효과를 모방하는 특성

 private void btnTest_Checked(object sender, RoutedEventArgs e)
 {
     btn2.IsChecked = false;
     btn3.IsChecked = false;
 }

RibbonToggleButtons를 위해 이 작업을 수행했지만 일반 ToggleButtons도 마찬가지일 수 있습니다.

여기서 EnumToBooleanConverter를 사용하여 각 버튼의 IsChecked를 "모드" 열거값에 바인딩했습니다. RadioButtons를 열거형으로 바인드하려면 어떻게 해야 합니까?( Converter Parameter 를 사용하여 이 버튼의 열거값을 지정합니다.각 버튼에 대해 1개의 열거값을 가져야 합니다.)

그런 다음 이미 선택된 버튼을 선택하지 않으려면 각 RibbonToggleButtons에 대한 클릭 이벤트에 대해 코드 뒤에 다음 내용을 입력합니다.

    private void PreventUncheckRibbonToggleButtonOnClick ( object sender, RoutedEventArgs e ) {

        // Prevent unchecking a checked toggle button - so that one always remains checked
        // Cancel the click if you hit an already-checked button

        var button = (RibbonToggleButton)sender;
        if( button.IsChecked != null ) { // Not sure why checked can be null but that's fine, ignore it
            bool notChecked = ( ! (bool)button.IsChecked );
            if( notChecked ){ // I guess this means the click would uncheck it
                button.IsChecked = true; 
            }
        }
    }

줄리안과 나 같은 사람들을 돕기 위해 (2분 전...)에서 얻을 수 있습니다.RadioButton이것처럼.

class RadioToggleButton : RadioButton
{
    protected override void OnToggle()
    {
        if (IsChecked == true) IsChecked = IsThreeState ? (bool?)null : (bool?)false;
        else IsChecked = IsChecked.HasValue;
    }
}

그럼 우데이 키란이 추천한 대로 쓰면 돼...

<Window x:Class="Sample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Sample"
    Title="MainWindow" Height="600" Width="600">
    <StackPanel>
        <local:RadioToggleButton Content="Button" Style="{StaticResource {x:Type ToggleButton}}" />
    </StackPanel>
</Window>

이 방법에서는 1개만 허용됩니다.ToggleButton되려고Checked한 번에 UnChecking도 가능합니다.

나는 몇 가지 답을 가져다가 코드를 추가했다.이제 하나의 전환 버튼처럼 작동하는 다른 전환 버튼 그룹을 가질 수 있습니다.

<UserControl.Resources>
    <Style x:Key="GroupToggleStyle" TargetType="ToggleButton">
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding GroupName, RelativeSource={RelativeSource Self}}" Value="Group1"/>
                    <Condition Binding="{Binding BooleanProperty}" Value="true"/>
                </MultiDataTrigger.Conditions>
                <MultiDataTrigger.Setters>
                    <Setter Property="IsChecked" Value="true"/>
                </MultiDataTrigger.Setters>
            </MultiDataTrigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

토글 버튼처럼 보이는 다양한 라디오 버튼 그룹:

<Radio Button GroupName="Group1" Style="{StaticResource {x:Type ToggleButton}}">
<Radio Button GroupName="Group1" Style="{StaticResource {x:Type ToggleButton}}">
<Radio Button GroupName="Group2" Style="{StaticResource {x:Type ToggleButton}}">
<Radio Button GroupName="Group3" Style="{StaticResource {x:Type ToggleButton}}">

간단한 구현 중 하나는 다음과 같은 코드의 플래그를 유지하는 것입니다.

ToggleButton _CurrentlyCheckedButton;

다음으로 모든 컨텍스트 Toggle Buttons에 Checked 이벤트핸들러를 1개 할당합니다

private void ToggleButton_Checked(object sender, RoutedEventArgs e)
{
   if (_CurrentlyCheckedButton != null)
      _CurrentlyCheckedButton.IsChecked = false;

   _CurrentlyCheckedButton = (sender as ToggleButton);
}

또한 하나의 체크되지 않은 이벤트핸들러:

private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)
{
    if (_CurrentlyCheckedButton == (sender as ToggleButton))
       _CurrentlyCheckedButton = null;
}

이렇게 하면 원하는 '제로 또는 원'을 선택할 수 있습니다.

언급URL : https://stackoverflow.com/questions/2362641/how-to-get-a-group-of-toggle-buttons-to-act-like-radio-buttons-in-wpf

반응형