Silverlight phone更新Datatemplate中绑定到列表框的按钮

时间:2012-05-17 20:54:24

标签: c# silverlight listbox windows-phone datatemplate

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
  <Grid.Resources><DataTemplate x:Key="mDataTemplate">
    <Button BorderBrush="#FF767171" Margin="10,10,0,0" Click="button1_Click" IsEnabled="{Binding Enabled}">
      <Button.Content>
        <Grid x:Name="ButtonGrid" Height="Auto" HorizontalAlignment="Left" erticalAlignment="Top">
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />                                 
          </Grid.RowDefinitions>
     <TextBlock Grid.Row="0" Height="Auto" HorizontalAlignment="Left" Text="{Binding TitleText}" VerticalAlignment="Top" Width="Auto"  FontSize="30" />
     <TextBlock Grid.Row="1" Height="Auto" HorizontalAlignment="Left" Text="{Binding DetailText}" VerticalAlignment="Top" Margin="10,0,0,0" Width="Auto"  FontSize="20" />
        </Grid> </Button.Content> </Button> </DataTemplate> </Grid.Resources>

    

我的代码。

public class AboutData
    {        
        public string TitleText { get; set; }
        public string DetailText { get; set; }
        public bool Enabled { get; set; }
    }
}

列表框的Loadevent

ObservableCollection<AboutData> aCollection = new ObservableCollection<AboutData>();
aCollection.Add(new AboutData { TitleText="Title1", DetailText="Detail1", Enabled= true});
aCollection.Add(new AboutData { TitleText="Title2", DetailText="Detail2", Enabled= true});
aCollection.Add(new AboutData { TitleText="Title3", DetailText="Detail3", Enabled= true});

ContentPanel.DataContext = aCollection;

当加载listBox1(我的列表框)时,我创建了一个关于AboutData的ObservableCollection并将其分配给ControlPanel.DataContext

我想在单击某个按钮时禁用我的lisbox中的按钮。 不知道怎么样。 帮助Apprciciated。

1 个答案:

答案 0 :(得分:0)

您应该能够设置AboutData的Enabled属性

public void button1_Click(object sender, RoutedEvent e)
{
  AboutData dataContext = (sender as Button).DataContext as AboutData;
  dataContext.Enabled = false;
}

此外,您需要在AboutData上实现INotifyPropertyChanged,以便绑定起作用(请参阅this

public class AboutData : INotifyPropertyChanged
{
    // boiler-plate
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    // props
    private string _Enabled;
    public string Enabled
    {
        get { return Enabled; }
        set { SetField(ref _Enabled, value, "Enabled"); }
    }

    // etc. for TitleText, DetailText
}