當我嘗試編譯以下代碼時,出現錯誤'可見性'成員無效,因爲它沒有限定類型名稱。如何使用觸發器更改TextBlock的可見性?
什麼是我必須改變,以便我可以使TextBlock消失當Status = off?
XAML:
<Window x:Class="TestTrigger123345.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBlock Text="This is a sentence.">
<TextBlock.Triggers>
<Trigger Property="{Binding Status}" Value="off">
<Setter Property="Visibility" Value="Collapsed"/>
</Trigger>
</TextBlock.Triggers>
</TextBlock>
<TextBlock Text="{Binding Status}"/>
</StackPanel>
</Window>
代碼背後:
using System.Windows;
namespace TestTrigger123345
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = this;
Status = "off";
}
public string Status { get; set; }
}
}
我改DataTrigger和依賴項屬性和它得到了同樣的錯誤:
XAML:
<Window x:Class="TestTrigger123345.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left">
<TextBlock Text="{Binding Status}">
<TextBlock.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="TextBlock.Background" Value="Tan"/>
</DataTrigger>
</TextBlock.Triggers>
</TextBlock>
</StackPanel>
</Window>
代碼背後:
using System.Windows;
namespace TestTrigger123345
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = this;
Status = "off";
}
#region DependencyProperty: Status
public string Status
{
get
{
return (string)GetValue(StatusProperty);
}
set
{
SetValue(StatusProperty, value);
}
}
public static readonly DependencyProperty StatusProperty =
DependencyProperty.Register("Status", typeof(string), typeof(Window1),
new FrameworkPropertyMetadata());
#endregion
}
}
我重做這與具有實現INotifyPropertyChanged的屬性狀態的視圖模型,並獲取相同的錯誤:
WindowViewModel.cs:
using System.ComponentModel;
namespace TestTrigger123345
{
class WindowViewModel
{
#region ViewModelProperty: Status
private string _status;
public string Status
{
get
{
return _status;
}
set
{
_status = value;
OnPropertyChanged("Status");
}
}
#endregion
#region PropertChanged Block
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
#endregion
}
}
代碼背後:
using System.Windows;
namespace TestTrigger123345
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
WindowViewModel windowViewModel = new WindowViewModel();
windowViewModel.Status = "off";
DataContext = windowViewModel;
}
}
}
當然還有一種方法用觸發某種方式來做到這一點。
我投了使用轉換器。 – gcores 2009-05-27 09:33:03
所以我的轉換器將採取一個字符串(狀態)並返回一個屬性的可見性?或者你的意思是迴歸整個元素?這將如何在代碼中實現? – 2009-05-27 09:49:13
我也用ViewModel(上面的代碼)重新實現了它,並且它得到相同的錯誤。 – 2009-05-27 09:56:08