2014-09-26 42 views
0

我試圖使ListBoxItem僅在布爾型isInEditMode爲true時才顯示。這是我的變量:在代碼中綁定到變量和轉換器

private bool isInEditMode 
{ 
    get { return Convert.ToBoolean(GetValue(IsInEditMode_Property)); } 
    set { SetValue(IsInEditMode_Property, value); } 
} 

public static readonly DependencyProperty IsInEditMode_Property = DependencyProperty.Register("isInEditMode", typeof(bool), typeof(MainWindow), new PropertyMetadata(null)); 

這是我加入ListBoxItem

SurfaceListBoxItem slbi = new SurfaceListBoxItem();  

Binding visibilityBinding = new Binding("Visibility"); 
visibilityBinding.Source = isInEditMode; 
visibilityBinding.Converter = new BoolToVisibility(); 
visibilityBinding.NotifyOnTargetUpdated = true; 
slbi.SetBinding(SurfaceListBoxItem.VisibilityProperty, visibilityBinding);      

myListBox.Items.Add(slbi); 

然而,轉換並沒有得到當isInEditMode改變觸發。什麼地方出了錯?這是我的轉換器順便說一句,非常直截了當:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    if (System.Convert.ToBoolean(value) == true) 
     return System.Windows.Visibility.Visible; 
    else 
     return System.Windows.Visibility.Collapsed; 
} 

我沒有在XAML快速測試,這工作雖然:

<Grid Visibility="{Binding Path=isInEditMode, ElementName=myMainWindow, Converter={StaticResource BoolToVisibility}, NotifyOnTargetUpdated=True}" /> 
+1

有亂盒'BooleanToVisibilityConverter':http://msdn.microsoft.com/en-us/library/system.windows.controls。 booleantovisibilityconverter%28v = vs.110%29.aspx – Dennis 2014-09-26 06:32:05

+0

感謝您的信息!我已經改變了它,但它仍然無法正常工作......我懷疑'visibilityBinding.Source = isInEditMode'有問題,它沒有綁定... – 2014-09-26 06:35:53

回答

1

你的Binding建設是錯誤的。 Source是對象,即綁定操作的數據源。 Path(通過ctor參數設置它)是數據源中數據屬性的路徑。

因此,Binding應該是這樣的:

var visibilityBinding = new Binding("isInEditMode"); 
visibilityBinding.Source = this; 
visibilityBinding.Converter = new BoolToVisibility(); 
visibilityBinding.NotifyOnTargetUpdated = true; 

// here you setting the target property - VisibilityProperty 
slbi.SetBinding(SurfaceListBoxItem.VisibilityProperty, visibilityBinding);