2016-06-22 85 views
-2

我想綁定一對ToggleButtons,所以當一個被選中時,另一個也被選中。WPF Programaticlly綁定兩種方式

ToggleButton two = new ToggleButton(); 
/* Set up ToggleButton here*/ 
ToggleButton one = this.somePanel.Children.FirstOrDefault(/*Some Condition*/) as ToggleButton 
if (one == null) return; 
Binding binding = new Binding("IsChecked"); 
binding.Source = two; 
binding.Mode = BindingMode.TwoWay; 
one.SetBinding(ToggleButton.IsCheckedProperty, binding); 
/* Add two to the UI */ 

當我切換按鈕一,按鈕二切換,但是,當我切換按鈕二,按鈕一不切換。

+3

不要在代碼中創建綁定,這是一個爛攤子。 –

+0

所以你想切換按鈕做正常切換按鈕做的相反嗎?爲什麼你需要一對按鈕是相同的? – Paparazzi

+0

@Paparazzi他們代表服務器上的同一個對象,但在不同的菜單中 – KevinA

回答

0

您可以在ViewModel兩個按鈕相同屬性的IsChecked屬性綁定。

MainWindow.xaml

<ToggleButton Grid.Row="1" 
        Grid.Column="0" 
        Width="60" 
        Height="30" 
        Content="Button 1" 
        IsChecked="{Binding IsToggleButtonChecked}" /> 
    <ToggleButton Grid.Row="1" 
        Grid.Column="1" 
        Width="60" 
        Height="30" 
        Content="Button 2" 
        IsChecked="{Binding IsToggleButtonChecked}" /> 

MainViewModel.cs(假設你可以使用MVVM Light):

private bool _isToggleButtonChecked = false; 
    public bool IsToggleButtonChecked 
    { 
     get { return _isToggleButtonChecked; } 
     set { Set<bool>(ref _isToggleButtonChecked, value); } 
    } 
-1

我不認爲你的代碼有任何問題。它似乎在我的最後工作完美。我已經嘗試了xaml和codebehind,以及完全在代碼背後。

兩者均按預期工作,裝訂完美!

我在下面包含了一個示例。覈實。綁定在我的最後完美無缺!

XAML:

<Window x:Class="WpfApplication1.MainWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:local="clr-namespace:WpfApplication1" 
xmlns:viewModel="clr-namespace:WpfApplication1.ViewModel" 
mc:Ignorable="d" 
Title="MainWindow" Height="350" Width="525" 
> 
<Grid x:Name="Grid1" /> 
</Window> 

代碼背後:

using System.Windows; 
using System.Windows.Controls.Primitives; 
using System.Windows.Data; 

namespace WpfApplication1 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      ToggleButton two = new ToggleButton(); 
      two.Content = "Two"; 
      two.Width = 100; 
      two.Height = 50; 

      /* Set up ToggleButton here*/ 

      this.Grid1.Children.Add(two); 

      ToggleButton one = new ToggleButton(); 
      if (one == null) return; 
      one.Content = "One"; 
      one.Width = 100; 
      one.Height = 50; 
      one.Margin = new Thickness(0, 0, 250, 0); 

      this.Grid1.Children.Add(one); 

      Binding binding = new Binding("IsChecked"); 
      binding.Source = two; 
      binding.Mode = BindingMode.TwoWay; 
      one.SetBinding(ToggleButton.IsCheckedProperty, binding); 
      /* Add two to the UI */ 
     } 
    } 
}