2012-06-28 221 views
0

我爲複選框製作了自定義圖片,並希望每次點擊圖片時都會在已選中和未選中的版本之間切換。我的源代碼:點擊更改圖片源

XAML

<CheckBox Name="checkBox1" Padding="0" BorderThickness="0" Margin="5" Grid.Row="1"> 
    <Image Name="image1" Margin="-14,0,0,0" Source="checkbox0.png" MouseDown="Image_MouseDown" Stretch="Uniform"/> 
</CheckBox> 

C#

private void Image_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    if (e.LeftButton == MouseButtonState.Pressed) 
    { 
     if (checkBox1checked) 
     { 
      image1.BeginInit(); 
      image1.Source = new BitmapImage(new Uri("/checkbox0.png", UriKind.RelativeOrAbsolute)); 
      image1.EndInit(); 
      checkBox1checked = false; 
     } 

     if (!checkBox1checked) 
     { 
      image1.BeginInit(); 
      image1.Source = new BitmapImage(new Uri("/checkbox1.png", UriKind.RelativeOrAbsolute)); 
      image1.EndInit(); 
      checkBox1checked = true; 
     } 
    } 
} 
+0

什麼是你的問題?它不起作用嗎?你有錯誤嗎?你有什麼嘗試? –

回答

3

使用取消選中,並在那裏

<CheckBox Name="checkBox1" Padding="0" Unchecked="chkbox_Unchecked" Checked="chkbox_Checked BorderThickness="0" Margin="5" Grid.Row="1"> 
    <Image Name="image1" Margin="-14,0,0,0" Source="checkbox0.png" Stretch="Uniform"/> 
</CheckBox> 




     private void chkbox_Checked(object sender, RoutedEventArgs e) 
     { 
      SetImage("/checkbox0.png"); 
     } 

     private void chkbox_Checked(object sender, RoutedEventArgs e) 
     { 
      SetImage("/checkbox1.png"); 
     } 

    private void SetImage(string path) 
    { 
     image1.BeginInit(); 
       image1.Source = new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute)); 
       image1.EndInit(); 

    } 
+0

Unchecked =「chkbox_Unchecked」Checked =「chkbox_Checked」 – JohnnBlade

+0

在代碼中犯了一個小錯誤,其中一個應該是chkbox_UnChecked – JohnnBlade

1
選中該複選框的情況下,並設置圖像源

因爲那裏我在你的代碼中是一個邏輯錯誤,第二個if語句會在第一個之後執行,如果你改變了複選框的值。

而且你內心的複選框定義的圖像,這在每次初始化圖像時不知何故重置複選框的值,考慮移動圖像複選框之外,或只使用一個公共標誌

<CheckBox Name="checkBox1" Padding="0" BorderThickness="0" Margin="5" Grid.Row="1"> 
</CheckBox> 
<Image Name="image1" Margin="-14,0,0,0" Source="checkbox0.png" MouseDown="Image_MouseDown" Stretch="Uniform"/> 

變化背後

private void Image_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     if (e.LeftButton == MouseButtonState.Pressed) 
     { 
      if (checkBox1checked) 
      { 
       image1.BeginInit(); 
       image1.Source = new BitmapImage(new Uri("/checkbox0.png", UriKind.RelativeOrAbsolute)); 
       image1.EndInit(); 
       checkBox1checked = false; 
      } 
      else 
      { 
       image1.BeginInit(); 
       image1.Source = new BitmapImage(new Uri("/checkbox1.png", UriKind.RelativeOrAbsolute)); 
       image1.EndInit(); 
       checkBox1checked = true; 
      } 
     } 
    } 
代碼
0

最好嘗試:

private void chkbox_Unchecked(object sender, RoutedEventArgs e) 
    { 
     SetImage("/checkbox1.png"); 
    } 

     private void chkbox_Checked(object sender, RoutedEventArgs e) 
    { 
     SetImage("/checkbox1.png"); 
    }