ObservableStack을 Stackoverflow answer에서 복사했습니다. 내가 공용 속성관찰 가능한 스택 <T>이 푸시에서 작동하지 않습니다.
public ObservableStack<int> myStack;
public MainPage()
{
myStack = new ObservableStack<int>();
this.InitializeComponent();
myButton.DataContext = myStack;
}
으로 뒤에 코드에서 스택을 정의
public class StackToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var collection = (Stack<int>)value;
return collection.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
:
public class ObservableStack<T> : Stack<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
public ObservableStack()
{
}
public ObservableStack(IEnumerable<T> collection)
{
foreach (var item in collection)
base.Push(item);
}
public ObservableStack(List<T> list)
{
foreach (var item in list)
base.Push(item);
}
public new virtual void Clear()
{
base.Clear();
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public new virtual T Pop()
{
var item = base.Pop();
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
return item;
}
public new virtual void Push(T item)
{
base.Push(item);
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
this.RaiseCollectionChanged(e);
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
this.RaisePropertyChanged(e);
}
protected virtual event PropertyChangedEventHandler PropertyChanged;
private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (this.CollectionChanged != null)
this.CollectionChanged(this, e);
}
private void RaisePropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add { this.PropertyChanged += value; }
remove { this.PropertyChanged -= value; }
}
}
그리고 지금 나는 다음 변환기 클래스를 사용하여 Stack.Count에 버튼의 가시성을 바인딩하는 것을 시도하고있다
및 XAML은 다음과 같습니다.
<Page.Resources>
<Converters:StackToVisibilityConverter x:Key="StackToVisibilityConverter"/>
</Page.Resources>
<Button x:Name="myButton" Content="Test Button" Visibility="{Binding Converter={StaticResource StackToVisibilityConverter}}"/>
다른 버튼 클릭 이벤트를 사용하여 int를 푸시하면 버튼이 여전히 보이지 않습니다. 무엇이 잘못 되었나요?
나는 그것이'에 대한'PropertyChanged'을 제기 코드를 찾을 수 없습니다 "카운트"'항목 (또는 어떤 다른 일 경우) 추가되거나 제거 될 때. Stack에서 OnPropertyChanged를 호출 할 것인지 궁금합니다. 당신이 거기에 브레이크 포인트를 설정할 때, 당신은 그것을 치는가? '새로운 '것도 의심 스럽다. 나는이 혼란을 없애고 ObservableCollection에서 파생 된 아마 관찰 가능한 스택을 작성했습니다. 그 중 하나 또는 ObservableCollection에 대한 푸시 및 팝 확장 메서드를 작성하고 맥주에 나가. –